@opra/client 0.11.8 → 0.12.0

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 (83) hide show
  1. package/cjs/index.min.mjs +1572 -1046
  2. package/esm/index.min.mjs +1558 -1046
  3. package/package.json +11 -11
  4. package/typings/common/filter/antlr/OpraFilterLexer.d.ts +1 -1
  5. package/typings/common/filter/antlr/OpraFilterListener.d.ts +1 -1
  6. package/typings/common/filter/ast/expressions/arithmetic-expression.d.ts +1 -1
  7. package/typings/common/filter/ast/expressions/comparison-expression.d.ts +1 -1
  8. package/typings/common/filter/ast/expressions/logical-expression.d.ts +1 -1
  9. package/typings/common/filter/build.d.ts +3 -3
  10. package/typings/common/filter/errors.d.ts +2 -0
  11. package/typings/common/filter/filter-tree-visitor.d.ts +2 -1
  12. package/typings/common/helpers/responsive-map.d.ts +19 -5
  13. package/typings/common/http/enums/{http-headers.enum.d.ts → http-headers-codes.enum.d.ts} +1 -1
  14. package/typings/common/http/enums/{http-status.enum.d.ts → http-status-codes.enum.d.ts} +1 -1
  15. package/typings/common/http/http-headers.d.ts +70 -0
  16. package/typings/common/http/http-param-codec.d.ts +4 -0
  17. package/typings/common/http/http-params.d.ts +99 -0
  18. package/typings/common/http/http-request-node.d.ts +34 -0
  19. package/typings/common/http/http-request.d.ts +73 -31
  20. package/typings/common/http/http-response.d.ts +41 -0
  21. package/typings/common/http/index.d.ts +13 -2
  22. package/typings/common/http/interfaces/client-http-headers.interface.d.ts +1 -1
  23. package/typings/common/http/interfaces/server-http-headers.interface.d.ts +1 -1
  24. package/typings/common/http/multipart/batch-multipart.d.ts +1 -1
  25. package/typings/common/http/multipart/http-request-content.d.ts +1 -1
  26. package/typings/common/http/multipart/http-response-content.d.ts +1 -1
  27. package/typings/common/http/param-codec/boolean-codec.d.ts +5 -0
  28. package/typings/common/http/param-codec/date-codec.d.ts +16 -0
  29. package/typings/common/http/param-codec/filter-codec.d.ts +6 -0
  30. package/typings/common/http/param-codec/integer-codec.d.ts +9 -0
  31. package/typings/common/http/param-codec/number-codec.d.ts +12 -0
  32. package/typings/common/http/param-codec/string-codec.d.ts +14 -0
  33. package/typings/common/http/utils/encodeURIParam.d.ts +1 -0
  34. package/typings/common/i18n/i18n.d.ts +6 -6
  35. package/typings/common/schema/decorators/opr-collection-resource.decorator.d.ts +1 -1
  36. package/typings/common/schema/decorators/opr-complex-type.decorator.d.ts +1 -1
  37. package/typings/common/schema/decorators/opr-simple-type.decorator.d.ts +1 -1
  38. package/typings/common/schema/decorators/opr-singleton-resource.decorator.d.ts +1 -1
  39. package/typings/common/schema/implementation/data-type/complex-type.d.ts +1 -1
  40. package/typings/common/schema/implementation/data-type/union-type.d.ts +1 -1
  41. package/typings/common/schema/implementation/document-builder.d.ts +1 -1
  42. package/typings/common/schema/implementation/opra-document.d.ts +2 -2
  43. package/typings/common/schema/implementation/query/collection-count-query.d.ts +1 -1
  44. package/typings/common/schema/implementation/query/collection-create-query.d.ts +1 -1
  45. package/typings/common/schema/implementation/query/collection-delete-many-query.d.ts +1 -1
  46. package/typings/common/schema/implementation/query/collection-get-query.d.ts +1 -1
  47. package/typings/common/schema/implementation/query/collection-search-query.d.ts +1 -1
  48. package/typings/common/schema/implementation/query/collection-update-many-query.d.ts +1 -1
  49. package/typings/common/schema/implementation/query/collection-update-query.d.ts +1 -1
  50. package/typings/common/schema/implementation/query/field-get-query.d.ts +1 -1
  51. package/typings/common/schema/implementation/query/index.d.ts +4 -4
  52. package/typings/common/schema/implementation/query/singleton-get-query.d.ts +1 -1
  53. package/typings/common/schema/implementation/resource/collection-resource-info.d.ts +2 -0
  54. package/typings/common/schema/interfaces/data-type.metadata.d.ts +4 -4
  55. package/typings/common/schema/interfaces/resource.metadata.d.ts +9 -9
  56. package/typings/common/schema/types.d.ts +8 -8
  57. package/typings/common/url/opra-url-path-component.d.ts +1 -1
  58. package/typings/common/url/opra-url-path.d.ts +24 -18
  59. package/typings/common/url/opra-url-search-params.d.ts +3 -42
  60. package/typings/common/url/opra-url.d.ts +38 -28
  61. package/typings/http/http-client.d.ts +30 -13
  62. package/typings/http/http-collection-service.d.ts +67 -13
  63. package/typings/http/http-request-host.d.ts +18 -0
  64. package/typings/http/http-singleton-service.d.ts +24 -6
  65. package/typings/http/http-types.d.ts +44 -21
  66. package/typings/http/requests/batch-request.d.ts +0 -18
  67. package/typings/http/requests/collection-create-request.d.ts +5 -10
  68. package/typings/http/requests/collection-delete-many-request.d.ts +5 -9
  69. package/typings/http/requests/collection-delete-request.d.ts +5 -10
  70. package/typings/http/requests/collection-get-request.d.ts +5 -10
  71. package/typings/http/requests/collection-search-request.d.ts +5 -9
  72. package/typings/http/requests/collection-update-many-request.d.ts +5 -10
  73. package/typings/http/requests/collection-update-request.d.ts +5 -11
  74. package/typings/http/requests/singleton-create-request.d.ts +7 -0
  75. package/typings/http/requests/singleton-delete-request.d.ts +7 -0
  76. package/typings/http/requests/singleton-get-request.d.ts +7 -0
  77. package/typings/index.d.ts +3 -4
  78. package/typings/interfaces/http-options.interface.d.ts +1 -1
  79. package/typings/interfaces/http-request-config.interface.d.ts +1 -1
  80. package/typings/http/http-request.d.ts +0 -25
  81. package/typings/http/http-response.d.ts +0 -14
  82. package/typings/http/requests/http-singleton-get-request.d.ts +0 -11
  83. package/typings/http/utils/merge-raw-http-requests.util.d.ts +0 -2
package/esm/index.min.mjs CHANGED
@@ -1,10 +1,13 @@
1
1
  import { Buffer } from 'buffer';
2
+ import { Readable } from '@browsery/stream';
3
+ import { Observable, lastValueFrom } from 'rxjs';
4
+ import 'tslib';
2
5
  import { tokenize, splitString } from 'fast-tokenizer';
3
6
  import fs from '@browsery/fs';
4
7
  import i18next from '@browsery/i18next';
5
8
  import path from 'path-browserify';
6
9
  import { toDateDef, toBoolean, toDate, toString, toInt, toNumber } from 'putil-varhelpers';
7
- import antlr4, { Token, DFA, Lexer, LexerATNSimulator, PredictionContextCache, ATNDeserializer, Parser, ParserATNSimulator, FailedPredicateException, RecognitionException, NoViableAltException, ATN, ParserRuleContext, ErrorListener, CharStream, CommonTokenStream } from '@browsery/antlr4';
10
+ import antlr4, { Token, DFA, Lexer, LexerATNSimulator, PredictionContextCache, ATNDeserializer, Parser, FailedPredicateException, ParserATNSimulator, RecognitionException, NoViableAltException, ATN, ParserRuleContext, ErrorListener, CharStream, CommonTokenStream } from '@browsery/antlr4';
8
11
  import Highland from '@browsery/highland';
9
12
  import { uid } from 'uid';
10
13
  export { uid } from 'uid';
@@ -13,10 +16,15 @@ import omit from 'lodash.omit';
13
16
  import promisify from 'putil-promisify';
14
17
  import isPlainObject from 'putil-isplainobject';
15
18
  import merge from 'putil-merge';
16
- import { EventEmitter } from 'events';
17
- import '@browsery/http-parser';
18
- import '@browsery/stream';
19
- import { Observable } from 'rxjs';
19
+ import { HTTPParser } from '@browsery/http-parser';
20
+
21
+ function isFunction(value) {
22
+ return typeof value === 'function';
23
+ }
24
+
25
+ function isReadableStreamLike(obj) {
26
+ return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);
27
+ }
20
28
 
21
29
  const dotPattern$1 = /^([^.]+)\.(.*)$/;
22
30
  function pathToTree$1(arr, lowerCaseKeys) {
@@ -157,10 +165,8 @@ class I18n extends BaseI18n {
157
165
  async loadResourceDir(dirnames, deep, overwrite) {
158
166
  for (const dirname of Array.isArray(dirnames) ? dirnames : [dirnames]) {
159
167
  /* istanbul ignore next */
160
- if (!(fs.statSync(dirname)).isDirectory()) {
161
- // eslint-disable-next-line no-console
168
+ if (!(fs.existsSync(dirname)))
162
169
  continue;
163
- }
164
170
  const languageDirs = fs.readdirSync(dirname);
165
171
  for (const lang of languageDirs) {
166
172
  const langDir = path.join(dirname, lang);
@@ -1118,10 +1124,6 @@ OpraFilterLexer.DecisionsToDFA = OpraFilterLexer._ATN.decisionToState.map((ds, i
1118
1124
 
1119
1125
  /* eslint-disable */
1120
1126
  class OpraFilterParser extends Parser {
1121
- constructor(input) {
1122
- super(input);
1123
- this._interp = new ParserATNSimulator(this, OpraFilterParser._ATN, OpraFilterParser.DecisionsToDFA, new PredictionContextCache());
1124
- }
1125
1127
  get grammarFileName() {
1126
1128
  return "OpraFilter.g4";
1127
1129
  }
@@ -1140,6 +1142,10 @@ class OpraFilterParser extends Parser {
1140
1142
  createFailedPredicateException(predicate, message) {
1141
1143
  return new FailedPredicateException(this, predicate, message);
1142
1144
  }
1145
+ constructor(input) {
1146
+ super(input);
1147
+ this._interp = new ParserATNSimulator(this, OpraFilterParser._ATN, OpraFilterParser.DecisionsToDFA, new PredictionContextCache());
1148
+ }
1143
1149
  // @RuleVersion(0)
1144
1150
  root() {
1145
1151
  let localctx = new RootContext(this, this._ctx, this.state);
@@ -3543,13 +3549,19 @@ class ExternalConstant extends Literal {
3543
3549
  }
3544
3550
  }
3545
3551
 
3546
- // Fix: antlr4 d.ts files is invalid
3552
+ // Fix: antlr4 d.ts files are invalid
3547
3553
  const ParseTreeVisitor = antlr4.tree.ParseTreeVisitor;
3548
3554
  class FilterTreeVisitor extends ParseTreeVisitor {
3549
3555
  constructor(options) {
3550
3556
  super();
3551
3557
  this._timeZone = options?.timeZone;
3552
3558
  }
3559
+ visitChildren(node) {
3560
+ const result = super.visitChildren(node);
3561
+ if (Array.isArray(result) && result.length < 2)
3562
+ return result[0];
3563
+ return result;
3564
+ }
3553
3565
  defaultResult() {
3554
3566
  return undefined;
3555
3567
  }
@@ -3654,7 +3666,7 @@ class OpraErrorListener extends ErrorListener {
3654
3666
  this.errors = errors;
3655
3667
  }
3656
3668
  syntaxError(recognizer, offendingSymbol, line, column, msg, e) {
3657
- this.errors.push(new FilterParseError(msg, { recognizer, offendingSymbol, line, e }));
3669
+ this.errors.push(new FilterParseError(msg, { recognizer, offendingSymbol, line, column, e }));
3658
3670
  }
3659
3671
  }
3660
3672
 
@@ -3795,51 +3807,51 @@ const _wrapEntryValue = (v) => {
3795
3807
  /**
3796
3808
  * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers#controls
3797
3809
  */
3798
- var HttpHeaders;
3799
- (function (HttpHeaders) {
3810
+ var HttpHeaderCodes;
3811
+ (function (HttpHeaderCodes) {
3800
3812
  /* *** Custom Headers *** */
3801
- HttpHeaders["X_Opra_Version"] = "X-Opra-Version";
3802
- HttpHeaders["X_Opra_DataType"] = "X-Opra-DataType";
3803
- HttpHeaders["X_Opra_Count"] = "X-Opra-Count";
3813
+ HttpHeaderCodes["X_Opra_Version"] = "X-Opra-Version";
3814
+ HttpHeaderCodes["X_Opra_DataType"] = "X-Opra-DataType";
3815
+ HttpHeaderCodes["X_Opra_Count"] = "X-Opra-Count";
3804
3816
  /* *** Authentication *** */
3805
3817
  /**
3806
3818
  * Defines the authentication method that should be used to access a resource.
3807
3819
  */
3808
- HttpHeaders["WWW_Authenticate"] = "WWW-Authenticate";
3820
+ HttpHeaderCodes["WWW_Authenticate"] = "WWW-Authenticate";
3809
3821
  /**
3810
3822
  * Contains the credentials to authenticate a user-agent with a server.
3811
3823
  */
3812
- HttpHeaders["Authorization"] = "Authorization";
3824
+ HttpHeaderCodes["Authorization"] = "Authorization";
3813
3825
  /**
3814
3826
  * Defines the authentication method that should be used to access a resource behind a proxy server.
3815
3827
  */
3816
- HttpHeaders["Proxy_Authenticate"] = "Proxy-Authenticate";
3828
+ HttpHeaderCodes["Proxy_Authenticate"] = "Proxy-Authenticate";
3817
3829
  /**
3818
3830
  * Contains the credentials to authenticate a user agent with a proxy server.
3819
3831
  */
3820
- HttpHeaders["Proxy_Authorization"] = "Proxy-Authorization";
3832
+ HttpHeaderCodes["Proxy_Authorization"] = "Proxy-Authorization";
3821
3833
  /* *** Caching *** */
3822
3834
  /**
3823
3835
  * The time, in seconds, that the object has been in a proxy cache.
3824
3836
  */
3825
- HttpHeaders["Age"] = "Age";
3837
+ HttpHeaderCodes["Age"] = "Age";
3826
3838
  /**
3827
3839
  * Directives for caching mechanisms in both requests and responses.
3828
3840
  */
3829
- HttpHeaders["Cache_Control"] = "Cache-Control";
3841
+ HttpHeaderCodes["Cache_Control"] = "Cache-Control";
3830
3842
  /**
3831
3843
  * Clears browsing data (e.g. cookies, storage, cache) associated with the requesting website.
3832
3844
  */
3833
- HttpHeaders["Clear_Site_Data"] = "Clear-Site-Data";
3845
+ HttpHeaderCodes["Clear_Site_Data"] = "Clear-Site-Data";
3834
3846
  /**
3835
3847
  * The date/time after which the response is considered stale.
3836
3848
  */
3837
- HttpHeaders["Expires"] = "Expires";
3849
+ HttpHeaderCodes["Expires"] = "Expires";
3838
3850
  /**
3839
3851
  * Implementation-specific header that may have various effects anywhere along the request-response chain.
3840
3852
  * Used for backwards compatibility with HTTP/1.0 caches where the Cache-Control header is not yet present.
3841
3853
  */
3842
- HttpHeaders["Pragma"] = "Pragma";
3854
+ HttpHeaderCodes["Pragma"] = "Pragma";
3843
3855
  /* *** Conditionals *** */
3844
3856
  /**
3845
3857
  * The last modification date of the resource, used to compare several versions of the same resource.
@@ -3847,294 +3859,294 @@ var HttpHeaders;
3847
3859
  * Conditional requests using If-Modified-Since and If-Unmodified-Since
3848
3860
  * use this value to change the behavior of the request.
3849
3861
  */
3850
- HttpHeaders["Last_Modified"] = "Last-Modified";
3862
+ HttpHeaderCodes["Last_Modified"] = "Last-Modified";
3851
3863
  /**
3852
3864
  * A unique string identifying the version of the resource.
3853
3865
  * Conditional requests using If-Match and If-None-Match use this value to change the behavior of the request.
3854
3866
  */
3855
- HttpHeaders["ETag"] = "ETag";
3867
+ HttpHeaderCodes["ETag"] = "ETag";
3856
3868
  /**
3857
3869
  * Makes the request conditional, and applies the method only if the stored resource matches one of the given ETags.
3858
3870
  */
3859
- HttpHeaders["If_Match"] = "If-Match";
3871
+ HttpHeaderCodes["If_Match"] = "If-Match";
3860
3872
  /**
3861
3873
  * Makes the request conditional, and applies the method only if the stored resource doesn't match
3862
3874
  * any of the given ETags. This is used to update caches (for safe requests), or to prevent uploading
3863
3875
  * a new resource when one already exists.
3864
3876
  */
3865
- HttpHeaders["If_None_Match"] = "If-None-Match";
3877
+ HttpHeaderCodes["If_None_Match"] = "If-None-Match";
3866
3878
  /**
3867
3879
  * Makes the request conditional, and expects the resource to be transmitted only if it has been modified
3868
3880
  * after the given date. This is used to transmit data only when the cache is out of date.
3869
3881
  */
3870
- HttpHeaders["If_Modified_Since"] = "If-Modified-Since";
3882
+ HttpHeaderCodes["If_Modified_Since"] = "If-Modified-Since";
3871
3883
  /**
3872
3884
  * Makes the request conditional, and expects the resource to be transmitted only if
3873
3885
  * it has not been modified after the given date. This ensures the coherence of a new
3874
3886
  * fragment of a specific range with previous ones, or to implement an optimistic
3875
3887
  * concurrency control system when modifying existing documents.
3876
3888
  */
3877
- HttpHeaders["If_Unmodified_Since"] = "If-Unmodified-Since";
3889
+ HttpHeaderCodes["If_Unmodified_Since"] = "If-Unmodified-Since";
3878
3890
  /**
3879
3891
  * Determines how to match request headers to decide whether a cached response can be used
3880
3892
  * rather than requesting a fresh one from the origin server.
3881
3893
  */
3882
- HttpHeaders["Vary"] = "Vary";
3894
+ HttpHeaderCodes["Vary"] = "Vary";
3883
3895
  /* *** Connection management *** */
3884
3896
  /**
3885
3897
  * Controls whether the network connection stays open after the current transaction finishes.
3886
3898
  */
3887
- HttpHeaders["Connection"] = "Connection";
3899
+ HttpHeaderCodes["Connection"] = "Connection";
3888
3900
  /**
3889
3901
  * Controls how long a persistent connection should stay open.
3890
3902
  */
3891
- HttpHeaders["Keep_Alive"] = "Keep-Alive";
3903
+ HttpHeaderCodes["Keep_Alive"] = "Keep-Alive";
3892
3904
  // Content negotiation
3893
3905
  /**
3894
3906
  * Informs the server about the types of data that can be sent back.
3895
3907
  */
3896
- HttpHeaders["Accept"] = "Accept";
3908
+ HttpHeaderCodes["Accept"] = "Accept";
3897
3909
  /**
3898
3910
  * The encoding algorithm, usually a compression algorithm, that can be used on the resource sent back.
3899
3911
  */
3900
- HttpHeaders["Accept_Encoding"] = "Accept-Encoding";
3912
+ HttpHeaderCodes["Accept_Encoding"] = "Accept-Encoding";
3901
3913
  /**
3902
3914
  * Informs the server about the human language the server is expected to send back.
3903
3915
  * This is a hint and is not necessarily under the full control of the user:
3904
3916
  * the server should always pay attention not to override an explicit user choice
3905
3917
  * (like selecting a language from a dropdown).
3906
3918
  */
3907
- HttpHeaders["Accept_Language"] = "Accept-Language";
3919
+ HttpHeaderCodes["Accept_Language"] = "Accept-Language";
3908
3920
  /* *** Controls *** */
3909
3921
  /**
3910
3922
  * Indicates expectations that need to be fulfilled by the server to properly handle the request.
3911
3923
  */
3912
- HttpHeaders["Expect"] = "Expect";
3924
+ HttpHeaderCodes["Expect"] = "Expect";
3913
3925
  /* *** Cookies *** */
3914
3926
  /**
3915
3927
  * Contains stored HTTP cookies previously sent by the server with the Set-Cookie header.
3916
3928
  */
3917
- HttpHeaders["Cookie"] = "Cookie";
3929
+ HttpHeaderCodes["Cookie"] = "Cookie";
3918
3930
  /**
3919
3931
  * Send cookies from the server to the user-agent.
3920
3932
  */
3921
- HttpHeaders["Set_Cookie"] = "Set-Cookie";
3933
+ HttpHeaderCodes["Set_Cookie"] = "Set-Cookie";
3922
3934
  /* *** CORS *** */
3923
3935
  /**
3924
3936
  * Indicates whether the response can be shared.
3925
3937
  */
3926
- HttpHeaders["Access_Control_Allow_Origin"] = "Access-Control-Allow-Origin";
3938
+ HttpHeaderCodes["Access_Control_Allow_Origin"] = "Access-Control-Allow-Origin";
3927
3939
  /**
3928
3940
  * Indicates whether the response to the request can be exposed when the credentials flag is true.
3929
3941
  */
3930
- HttpHeaders["Access_Control_Allow_Credentials"] = "Access-Control-Allow-Credentials";
3942
+ HttpHeaderCodes["Access_Control_Allow_Credentials"] = "Access-Control-Allow-Credentials";
3931
3943
  /**
3932
3944
  * Used in response to a preflight request to indicate which HTTP headers can be used when making the actual request.
3933
3945
  */
3934
- HttpHeaders["Access_Control_Allow_Headers"] = "Access-Control-Allow-Headers";
3946
+ HttpHeaderCodes["Access_Control_Allow_Headers"] = "Access-Control-Allow-Headers";
3935
3947
  /**
3936
3948
  * Specifies the methods allowed when accessing the resource in response to a preflight request.
3937
3949
  */
3938
- HttpHeaders["Access_Control_Allow_Methods"] = "Access-Control-Allow-Methods";
3950
+ HttpHeaderCodes["Access_Control_Allow_Methods"] = "Access-Control-Allow-Methods";
3939
3951
  /**
3940
3952
  * Indicates which headers can be exposed as part of the response by listing their names.
3941
3953
  */
3942
- HttpHeaders["Access_Control_Expose_Headers"] = "Access-Control-Expose-Headers";
3954
+ HttpHeaderCodes["Access_Control_Expose_Headers"] = "Access-Control-Expose-Headers";
3943
3955
  /**
3944
3956
  * Indicates how long the results of a preflight request can be cached.
3945
3957
  */
3946
- HttpHeaders["Access_Control_Max_Age"] = "Access-Control-Max-Age";
3958
+ HttpHeaderCodes["Access_Control_Max_Age"] = "Access-Control-Max-Age";
3947
3959
  /**
3948
3960
  * Used when issuing a preflight request to let the server know which HTTP headers will be
3949
3961
  * used when the actual request is made.
3950
3962
  */
3951
- HttpHeaders["Access_Control_Request_Headers"] = "Access-Control-Request-Headers";
3963
+ HttpHeaderCodes["Access_Control_Request_Headers"] = "Access-Control-Request-Headers";
3952
3964
  /**
3953
3965
  * Used when issuing a preflight request to let the server know which HTTP method
3954
3966
  * will be used when the actual request is made.
3955
3967
  */
3956
- HttpHeaders["Access_Control_Request_Method"] = "Access-Control-Request-Method";
3968
+ HttpHeaderCodes["Access_Control_Request_Method"] = "Access-Control-Request-Method";
3957
3969
  /**
3958
3970
  * Indicates where a fetch originates from.
3959
3971
  */
3960
- HttpHeaders["Origin"] = "Origin";
3972
+ HttpHeaderCodes["Origin"] = "Origin";
3961
3973
  /**
3962
3974
  * Specifies origins that are allowed to see values of attributes retrieved via features of the Resource Timing API,
3963
3975
  * which would otherwise be reported as zero due to cross-origin restrictions.
3964
3976
  */
3965
- HttpHeaders["Timing_Allow_Origin"] = "Timing-Allow-Origin";
3977
+ HttpHeaderCodes["Timing_Allow_Origin"] = "Timing-Allow-Origin";
3966
3978
  /* *** Downloads *** */
3967
3979
  /**
3968
3980
  * Indicates if the resource transmitted should be displayed inline (default behavior without the header),
3969
3981
  * or if it should be handled like a download and the browser should present a "Save As" dialog.
3970
3982
  */
3971
- HttpHeaders["Content_Disposition"] = "Content-Disposition";
3983
+ HttpHeaderCodes["Content_Disposition"] = "Content-Disposition";
3972
3984
  /* *** Message body information *** */
3973
3985
  /**
3974
3986
  * Indicates to uniquely identifies MIME entities in several contexts.
3975
3987
  */
3976
- HttpHeaders["Content_ID"] = "Content-ID";
3988
+ HttpHeaderCodes["Content_ID"] = "Content-ID";
3977
3989
  /**
3978
3990
  * The size of the resource, in decimal number of bytes.
3979
3991
  */
3980
- HttpHeaders["Content_Length"] = "Content-Length";
3992
+ HttpHeaderCodes["Content_Length"] = "Content-Length";
3981
3993
  /**
3982
3994
  * Indicates the media type of the resource.
3983
3995
  */
3984
- HttpHeaders["Content_Type"] = "Content-Type";
3996
+ HttpHeaderCodes["Content_Type"] = "Content-Type";
3985
3997
  /**
3986
3998
  * Indicates to specify how a MIME message or body part has been encoded,
3987
3999
  * so that it can be decoded by its recipient.
3988
4000
  */
3989
- HttpHeaders["Content_Transfer_Encoding"] = "Content-Transfer-Encoding";
4001
+ HttpHeaderCodes["Content_Transfer_Encoding"] = "Content-Transfer-Encoding";
3990
4002
  /**
3991
4003
  * Used to specify the compression algorithm.
3992
4004
  */
3993
- HttpHeaders["Content_Encoding"] = "Content-Encoding";
4005
+ HttpHeaderCodes["Content_Encoding"] = "Content-Encoding";
3994
4006
  /**
3995
4007
  * Describes the human language(s) intended for the audience, so that it allows a user to
3996
4008
  * differentiate according to the users' own preferred language.
3997
4009
  */
3998
- HttpHeaders["Content_Language"] = "Content-Language";
4010
+ HttpHeaderCodes["Content_Language"] = "Content-Language";
3999
4011
  /**
4000
4012
  * Indicates an alternate location for the returned data.
4001
4013
  */
4002
- HttpHeaders["Content_Location"] = "Content-Location";
4014
+ HttpHeaderCodes["Content_Location"] = "Content-Location";
4003
4015
  // Proxies
4004
4016
  /**
4005
4017
  * Contains information from the client-facing side of proxy servers that is altered or
4006
4018
  * lost when a proxy is involved in the path of the request.
4007
4019
  */
4008
- HttpHeaders["Forwarded"] = "Forwarded";
4020
+ HttpHeaderCodes["Forwarded"] = "Forwarded";
4009
4021
  /**
4010
4022
  * Identifies the originating IP addresses of a client connecting to a web server
4011
4023
  * through an HTTP proxy or a load balancer.
4012
4024
  */
4013
- HttpHeaders["X_Forwarded_For"] = "X-Forwarded-For";
4025
+ HttpHeaderCodes["X_Forwarded_For"] = "X-Forwarded-For";
4014
4026
  /**
4015
4027
  * Identifies the original host requested that a client used to connect to your proxy or load balancer.
4016
4028
  */
4017
- HttpHeaders["X_Forwarded_Host"] = "X-Forwarded-Host";
4029
+ HttpHeaderCodes["X_Forwarded_Host"] = "X-Forwarded-Host";
4018
4030
  /**
4019
4031
  * Identifies the protocol (HTTP or HTTPS) that a client used to connect to your proxy or load balancer.
4020
4032
  */
4021
- HttpHeaders["X_Forwarded_Proto"] = "X-Forwarded-Proto";
4033
+ HttpHeaderCodes["X_Forwarded_Proto"] = "X-Forwarded-Proto";
4022
4034
  /**
4023
4035
  * Added by proxies, both forward and reverse proxies, and can appear in the request headers and the response headers.
4024
4036
  */
4025
- HttpHeaders["Via"] = "Via";
4037
+ HttpHeaderCodes["Via"] = "Via";
4026
4038
  /* *** Redirects *** */
4027
4039
  /**
4028
4040
  * Indicates the URL to redirect a page to.
4029
4041
  */
4030
- HttpHeaders["Location"] = "Location";
4042
+ HttpHeaderCodes["Location"] = "Location";
4031
4043
  /* *** Request context *** */
4032
4044
  /**
4033
4045
  * Contains an Internet email address for a human user who controls the requesting user agent.
4034
4046
  */
4035
- HttpHeaders["From"] = "From";
4047
+ HttpHeaderCodes["From"] = "From";
4036
4048
  /**
4037
4049
  * Specifies the domain name of the server (for virtual hosting), and (optionally)
4038
4050
  * the TCP port number on which the server is listening.
4039
4051
  */
4040
- HttpHeaders["Host"] = "Host";
4052
+ HttpHeaderCodes["Host"] = "Host";
4041
4053
  /**
4042
4054
  * The address of the previous web page from which a link to the currently requested page was followed.
4043
4055
  */
4044
- HttpHeaders["Referer"] = "Referer";
4056
+ HttpHeaderCodes["Referer"] = "Referer";
4045
4057
  /**
4046
4058
  * Governs which referrer information sent in the Referer header should be included with requests made.
4047
4059
  */
4048
- HttpHeaders["Referrer_Policy"] = "Referrer-Policy";
4060
+ HttpHeaderCodes["Referrer_Policy"] = "Referrer-Policy";
4049
4061
  /**
4050
4062
  * Contains a characteristic string that allows the network protocol peers to identify the application type,
4051
4063
  * operating system, software vendor or software version of the requesting software user agent.
4052
4064
  */
4053
- HttpHeaders["User_Agent"] = "User-Agent";
4065
+ HttpHeaderCodes["User_Agent"] = "User-Agent";
4054
4066
  /* *** Response context *** */
4055
4067
  /**
4056
4068
  * Lists the set of HTTP request methods supported by a resource.
4057
4069
  */
4058
- HttpHeaders["Allow"] = "Allow";
4070
+ HttpHeaderCodes["Allow"] = "Allow";
4059
4071
  /**
4060
4072
  * Contains information about the software used by the origin server to handle the request.
4061
4073
  */
4062
- HttpHeaders["Server"] = "Server";
4074
+ HttpHeaderCodes["Server"] = "Server";
4063
4075
  /* *** Range requests *** */
4064
4076
  /**
4065
4077
  * Indicates if the server supports range requests, and if so in which unit the range can be expressed.
4066
4078
  */
4067
- HttpHeaders["Accept_Ranges"] = "Accept-Ranges";
4079
+ HttpHeaderCodes["Accept_Ranges"] = "Accept-Ranges";
4068
4080
  /**
4069
4081
  * Indicates the part of a document that the server should return.
4070
4082
  */
4071
- HttpHeaders["Range"] = "Range";
4083
+ HttpHeaderCodes["Range"] = "Range";
4072
4084
  /**
4073
4085
  * Creates a conditional range request that is only fulfilled if the given etag or date matches
4074
4086
  * the remote resource. Used to prevent downloading two ranges from incompatible version of the resource.
4075
4087
  */
4076
- HttpHeaders["If_Range"] = "If-Range";
4088
+ HttpHeaderCodes["If_Range"] = "If-Range";
4077
4089
  /**
4078
4090
  * Indicates where in a full body message a partial message belongs.
4079
4091
  */
4080
- HttpHeaders["Content_Range"] = "Content-Range";
4092
+ HttpHeaderCodes["Content_Range"] = "Content-Range";
4081
4093
  /* *** Security *** */
4082
4094
  /**
4083
4095
  * Allows a server to declare an embedder policy for a given document.
4084
4096
  */
4085
- HttpHeaders["Cross_Origin_Embedder_Policy"] = "Cross-Origin-Embedder-Policy";
4097
+ HttpHeaderCodes["Cross_Origin_Embedder_Policy"] = "Cross-Origin-Embedder-Policy";
4086
4098
  /**
4087
4099
  * Prevents other domains from opening/controlling a window.
4088
4100
  */
4089
- HttpHeaders["Cross_Origin_Opener_Policy"] = "Cross-Origin-Opener-Policy";
4101
+ HttpHeaderCodes["Cross_Origin_Opener_Policy"] = "Cross-Origin-Opener-Policy";
4090
4102
  /**
4091
4103
  * Prevents other domains from reading the response of the resources to which this header is applied.
4092
4104
  */
4093
- HttpHeaders["Cross_Origin_Resource_Policy"] = "Cross-Origin-Resource-Policy";
4105
+ HttpHeaderCodes["Cross_Origin_Resource_Policy"] = "Cross-Origin-Resource-Policy";
4094
4106
  /**
4095
4107
  * Controls resources the user agent is allowed to load for a given page.
4096
4108
  */
4097
- HttpHeaders["Content_Security_Policy"] = "Content-Security-Policy";
4109
+ HttpHeaderCodes["Content_Security_Policy"] = "Content-Security-Policy";
4098
4110
  /**
4099
4111
  * Allows web developers to experiment with policies by monitoring, but not enforcing, their effects.
4100
4112
  * These violation reports consist of JSON documents sent via an HTTP POST request to the specified URI.
4101
4113
  */
4102
- HttpHeaders["Content_Security_Policy_Report_Only"] = "Content-Security-Policy-Report-Only";
4114
+ HttpHeaderCodes["Content_Security_Policy_Report_Only"] = "Content-Security-Policy-Report-Only";
4103
4115
  /**
4104
4116
  * Allows sites to opt in to reporting and/or enforcement of Certificate Transparency requirements,
4105
4117
  * which prevents the use of misissued certificates for that site from going unnoticed.
4106
4118
  * When a site enables the Expect-CT header, they are requesting that Chrome check that
4107
4119
  * any certificate for that site appears in public CT logs.
4108
4120
  */
4109
- HttpHeaders["Expect_CT"] = "Expect-CT";
4121
+ HttpHeaderCodes["Expect_CT"] = "Expect-CT";
4110
4122
  /**
4111
4123
  * Provides a mechanism to allow and deny the use of browser features in its own frame,
4112
4124
  * and in iframes that it embeds.
4113
4125
  */
4114
- HttpHeaders["Feature_Policy"] = "Feature-Policy";
4126
+ HttpHeaderCodes["Feature_Policy"] = "Feature-Policy";
4115
4127
  /**
4116
4128
  * Force communication using HTTPS instead of HTTP.
4117
4129
  */
4118
- HttpHeaders["Strict_Transport_Security"] = "Strict-Transport-Security";
4130
+ HttpHeaderCodes["Strict_Transport_Security"] = "Strict-Transport-Security";
4119
4131
  /**
4120
4132
  * Sends a signal to the server expressing the client's preference for an encrypted and authenticated response,
4121
4133
  * and that it can successfully handle the upgrade-insecure-requests directive.
4122
4134
  */
4123
- HttpHeaders["Upgrade_Insecure_Requests"] = "Upgrade-Insecure-Requests";
4135
+ HttpHeaderCodes["Upgrade_Insecure_Requests"] = "Upgrade-Insecure-Requests";
4124
4136
  /**
4125
4137
  * Disables MIME sniffing and forces browser to use the type given in Content-Type.
4126
4138
  */
4127
- HttpHeaders["X_Content_Type_Options"] = "X-Content-Type-Options";
4139
+ HttpHeaderCodes["X_Content_Type_Options"] = "X-Content-Type-Options";
4128
4140
  /**
4129
4141
  * The X-Download-Options HTTP header indicates that the browser (Internet Explorer)
4130
4142
  * should not display the option to "Open" a file that has been downloaded from an application,
4131
4143
  * to prevent phishing attacks as the file otherwise would gain access to execute in the context of the application.
4132
4144
  */
4133
- HttpHeaders["X_Download_Options"] = "X-Download-Options";
4145
+ HttpHeaderCodes["X_Download_Options"] = "X-Download-Options";
4134
4146
  /**
4135
4147
  * Indicates whether a browser should be allowed to render a page in a <frame>, <iframe>, <embed> or <object>.
4136
4148
  */
4137
- HttpHeaders["X_Frame_Options"] = "X-Frame-Options";
4149
+ HttpHeaderCodes["X_Frame_Options"] = "X-Frame-Options";
4138
4150
  /**
4139
4151
  * Specifies if a cross-domain policy file (crossdomain.xml) is allowed.
4140
4152
  * The file may define a policy to grant clients, such as Adobe's Flash Player (now obsolete),
@@ -4142,182 +4154,182 @@ var HttpHeaders;
4142
4154
  * permission to handle data across domains that would otherwise be restricted
4143
4155
  * due to the Same-Origin Policy. See the Cross-domain Policy File Specification for more information.
4144
4156
  */
4145
- HttpHeaders["X_Permitted_Cross_Domain_Policies"] = "X-Permitted-Cross-Domain-Policies";
4157
+ HttpHeaderCodes["X_Permitted_Cross_Domain_Policies"] = "X-Permitted-Cross-Domain-Policies";
4146
4158
  /**
4147
4159
  * May be set by hosting environments or other frameworks and contains information about
4148
4160
  * them while not providing any usefulness to the application or its visitors.
4149
4161
  * Unset this header to avoid exposing potential vulnerabilities.
4150
4162
  */
4151
- HttpHeaders["X_Powered_By"] = "X-Powered-By";
4163
+ HttpHeaderCodes["X_Powered_By"] = "X-Powered-By";
4152
4164
  /**
4153
4165
  * Enables cross-site scripting filtering.
4154
4166
  */
4155
- HttpHeaders["X_XSS_Protection"] = "X-XSS-Protection";
4167
+ HttpHeaderCodes["X_XSS_Protection"] = "X-XSS-Protection";
4156
4168
  /* *** Transfer coding *** */
4157
4169
  /**
4158
4170
  * Specifies the form of encoding used to safely transfer the resource to the user.
4159
4171
  */
4160
- HttpHeaders["Transfer_Encoding"] = "Transfer-Encoding";
4172
+ HttpHeaderCodes["Transfer_Encoding"] = "Transfer-Encoding";
4161
4173
  /**
4162
4174
  * Specifies the transfer encodings the user agent is willing to accept.
4163
4175
  */
4164
- HttpHeaders["TE"] = "TE";
4176
+ HttpHeaderCodes["TE"] = "TE";
4165
4177
  /**
4166
4178
  * Allows the sender to include additional fields at the end of chunked message.
4167
4179
  */
4168
- HttpHeaders["Trailer"] = "Trailer";
4180
+ HttpHeaderCodes["Trailer"] = "Trailer";
4169
4181
  /* *** WebSockets *** */
4170
- HttpHeaders["Sec_WebSocket_Key"] = "Sec-WebSocket-Key";
4171
- HttpHeaders["Sec_WebSocket_Extensions"] = "Sec-WebSocket-Extensions";
4172
- HttpHeaders["Sec_WebSocket_Accept"] = "Sec-WebSocket-Accept";
4173
- HttpHeaders["Sec_WebSocket_Protocol"] = "Sec-WebSocket-Protocol";
4174
- HttpHeaders["Sec_WebSocket_Version"] = "Sec-WebSocket-Version";
4182
+ HttpHeaderCodes["Sec_WebSocket_Key"] = "Sec-WebSocket-Key";
4183
+ HttpHeaderCodes["Sec_WebSocket_Extensions"] = "Sec-WebSocket-Extensions";
4184
+ HttpHeaderCodes["Sec_WebSocket_Accept"] = "Sec-WebSocket-Accept";
4185
+ HttpHeaderCodes["Sec_WebSocket_Protocol"] = "Sec-WebSocket-Protocol";
4186
+ HttpHeaderCodes["Sec_WebSocket_Version"] = "Sec-WebSocket-Version";
4175
4187
  /* *** Other *** */
4176
4188
  /**
4177
4189
  * Contains the date and time at which the message was originated.
4178
4190
  */
4179
- HttpHeaders["Date"] = "Date";
4191
+ HttpHeaderCodes["Date"] = "Date";
4180
4192
  /**
4181
4193
  * Indicates how long the user agent should wait before making a follow-up request.
4182
4194
  */
4183
- HttpHeaders["Retry_After"] = "Retry-After";
4195
+ HttpHeaderCodes["Retry_After"] = "Retry-After";
4184
4196
  /**
4185
4197
  * Communicates one or more metrics and descriptions for the given request-response cycle.
4186
4198
  */
4187
- HttpHeaders["Server_Timing"] = "Server-Timing";
4199
+ HttpHeaderCodes["Server_Timing"] = "Server-Timing";
4188
4200
  /**
4189
4201
  * Controls DNS prefetching, a feature by which browsers proactively perform domain name
4190
4202
  * resolution on both links that the user may choose to follow as well as URLs for items
4191
4203
  * referenced by the document, including images, CSS, JavaScript, and so forth.
4192
4204
  */
4193
- HttpHeaders["X_DNS_Prefetch_Control"] = "X-DNS-Prefetch-Control";
4194
- })(HttpHeaders || (HttpHeaders = {}));
4205
+ HttpHeaderCodes["X_DNS_Prefetch_Control"] = "X-DNS-Prefetch-Control";
4206
+ })(HttpHeaderCodes || (HttpHeaderCodes = {}));
4195
4207
 
4196
4208
  // noinspection JSUnusedGlobalSymbols
4197
4209
  /**
4198
4210
  * https://developer.mozilla.org/en-US/docs/Web/HTTP/Status#successful_responses
4199
4211
  */
4200
- var HttpStatus;
4201
- (function (HttpStatus) {
4212
+ var HttpStatusCodes;
4213
+ (function (HttpStatusCodes) {
4202
4214
  /* *** Information responses *** */
4203
4215
  /**
4204
4216
  * This interim response indicates that the client should continue the request or
4205
4217
  * ignore the response if the request is already finished.
4206
4218
  */
4207
- HttpStatus[HttpStatus["CONTINUE"] = 100] = "CONTINUE";
4219
+ HttpStatusCodes[HttpStatusCodes["CONTINUE"] = 100] = "CONTINUE";
4208
4220
  /**
4209
4221
  * This code is sent in response to an Upgrade request header from the client and
4210
4222
  * indicates the protocol the server is switching to.
4211
4223
  */
4212
- HttpStatus[HttpStatus["SWITCHING_PROTOCOLS"] = 101] = "SWITCHING_PROTOCOLS";
4224
+ HttpStatusCodes[HttpStatusCodes["SWITCHING_PROTOCOLS"] = 101] = "SWITCHING_PROTOCOLS";
4213
4225
  /**
4214
4226
  * This code indicates that the server has received and is processing the request, but no response is available yet.
4215
4227
  */
4216
- HttpStatus[HttpStatus["PROCESSING"] = 102] = "PROCESSING";
4228
+ HttpStatusCodes[HttpStatusCodes["PROCESSING"] = 102] = "PROCESSING";
4217
4229
  /**
4218
4230
  * This status code is primarily intended to be used with the Link header, letting the user agent
4219
4231
  * start preloading resources while the server prepares a response.
4220
4232
  */
4221
- HttpStatus[HttpStatus["EARLYHINTS"] = 103] = "EARLYHINTS";
4233
+ HttpStatusCodes[HttpStatusCodes["EARLYHINTS"] = 103] = "EARLYHINTS";
4222
4234
  /* *** Successful responses *** */
4223
4235
  /**
4224
4236
  * The request succeeded.
4225
4237
  */
4226
- HttpStatus[HttpStatus["OK"] = 200] = "OK";
4238
+ HttpStatusCodes[HttpStatusCodes["OK"] = 200] = "OK";
4227
4239
  /**
4228
4240
  * The request succeeded, and a new resource was created as a result.
4229
4241
  * This is typically the response sent after POST requests, or some PUT requests.
4230
4242
  */
4231
- HttpStatus[HttpStatus["CREATED"] = 201] = "CREATED";
4243
+ HttpStatusCodes[HttpStatusCodes["CREATED"] = 201] = "CREATED";
4232
4244
  /**
4233
4245
  * The request has been received but not yet acted upon. It is noncommittal,
4234
4246
  * since there is no way in HTTP to later send an asynchronous response indicating
4235
4247
  * the outcome of the request. It is intended for cases where another process or
4236
4248
  * server handles the request, or for batch processing.
4237
4249
  */
4238
- HttpStatus[HttpStatus["ACCEPTED"] = 202] = "ACCEPTED";
4250
+ HttpStatusCodes[HttpStatusCodes["ACCEPTED"] = 202] = "ACCEPTED";
4239
4251
  /**
4240
4252
  * This response code means the returned metadata is not exactly the same as is available from
4241
4253
  * the origin server, but is collected from a local or a third-party copy. This is mostly used
4242
4254
  * for mirrors or backups of another resource. Except for that specific case, the 200 OK
4243
4255
  * response is preferred to this status.
4244
4256
  */
4245
- HttpStatus[HttpStatus["NON_AUTHORITATIVE_INFORMATION"] = 203] = "NON_AUTHORITATIVE_INFORMATION";
4257
+ HttpStatusCodes[HttpStatusCodes["NON_AUTHORITATIVE_INFORMATION"] = 203] = "NON_AUTHORITATIVE_INFORMATION";
4246
4258
  /**
4247
4259
  * There is no content to send for this request, but the headers may be useful.
4248
4260
  * The user agent may update its cached headers for this resource with the new ones.
4249
4261
  */
4250
- HttpStatus[HttpStatus["NO_CONTENT"] = 204] = "NO_CONTENT";
4262
+ HttpStatusCodes[HttpStatusCodes["NO_CONTENT"] = 204] = "NO_CONTENT";
4251
4263
  /**
4252
4264
  * Tells the user agent to reset the document which sent this request.
4253
4265
  */
4254
- HttpStatus[HttpStatus["RESET_CONTENT"] = 205] = "RESET_CONTENT";
4266
+ HttpStatusCodes[HttpStatusCodes["RESET_CONTENT"] = 205] = "RESET_CONTENT";
4255
4267
  /**
4256
4268
  * This response code is used when the Range header is sent from the client to request only part of a resource.
4257
4269
  */
4258
- HttpStatus[HttpStatus["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT";
4270
+ HttpStatusCodes[HttpStatusCodes["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT";
4259
4271
  /* *** Redirection messages *** */
4260
4272
  /**
4261
4273
  * The request has more than one possible response. The user agent or user should choose one of them.
4262
4274
  * (There is no standardized way of choosing one of the responses, but HTML links to the possibilities
4263
4275
  * are recommended so the user can pick.)
4264
4276
  */
4265
- HttpStatus[HttpStatus["AMBIGUOUS"] = 300] = "AMBIGUOUS";
4277
+ HttpStatusCodes[HttpStatusCodes["AMBIGUOUS"] = 300] = "AMBIGUOUS";
4266
4278
  /**
4267
4279
  * The URL of the requested resource has been changed permanently. The new URL is given in the response.
4268
4280
  */
4269
- HttpStatus[HttpStatus["MOVED_PERMANENTLY"] = 301] = "MOVED_PERMANENTLY";
4281
+ HttpStatusCodes[HttpStatusCodes["MOVED_PERMANENTLY"] = 301] = "MOVED_PERMANENTLY";
4270
4282
  /**
4271
4283
  * This response code means that the URI of requested resource has been changed temporarily.
4272
4284
  * Further changes in the URI might be made in the future. Therefore, this same URI should
4273
4285
  * be used by the client in future requests.
4274
4286
  */
4275
- HttpStatus[HttpStatus["FOUND"] = 302] = "FOUND";
4287
+ HttpStatusCodes[HttpStatusCodes["FOUND"] = 302] = "FOUND";
4276
4288
  /**
4277
4289
  * This is used for caching purposes. It tells the client that the response has not been modified,
4278
4290
  * so the client can continue to use the same cached version of the response.
4279
4291
  */
4280
- HttpStatus[HttpStatus["SEE_OTHER"] = 303] = "SEE_OTHER";
4292
+ HttpStatusCodes[HttpStatusCodes["SEE_OTHER"] = 303] = "SEE_OTHER";
4281
4293
  /**
4282
4294
  *
4283
4295
  */
4284
- HttpStatus[HttpStatus["NOT_MODIFIED"] = 304] = "NOT_MODIFIED";
4296
+ HttpStatusCodes[HttpStatusCodes["NOT_MODIFIED"] = 304] = "NOT_MODIFIED";
4285
4297
  /**
4286
4298
  * The server sends this response to direct the client to get the requested resource at another
4287
4299
  * URI with same method that was used in the prior request. This has the same semantics as
4288
4300
  * the 302 Found HTTP response code, with the exception that the user agent must not change
4289
4301
  * the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
4290
4302
  */
4291
- HttpStatus[HttpStatus["TEMPORARY_REDIRECT"] = 307] = "TEMPORARY_REDIRECT";
4303
+ HttpStatusCodes[HttpStatusCodes["TEMPORARY_REDIRECT"] = 307] = "TEMPORARY_REDIRECT";
4292
4304
  /**
4293
4305
  * This means that the resource is now permanently located at another URI, specified by the Location:
4294
4306
  * HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code,
4295
4307
  * with the exception that the user agent must not change the HTTP method used: if a POST was used
4296
4308
  * in the first request, a POST must be used in the second request.
4297
4309
  */
4298
- HttpStatus[HttpStatus["PERMANENT_REDIRECT"] = 308] = "PERMANENT_REDIRECT";
4310
+ HttpStatusCodes[HttpStatusCodes["PERMANENT_REDIRECT"] = 308] = "PERMANENT_REDIRECT";
4299
4311
  /* *** Client error responses *** */
4300
4312
  /**
4301
4313
  * The server cannot or will not process the request due to something that is perceived to be a client error
4302
4314
  * (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
4303
4315
  */
4304
- HttpStatus[HttpStatus["BAD_REQUEST"] = 400] = "BAD_REQUEST";
4316
+ HttpStatusCodes[HttpStatusCodes["BAD_REQUEST"] = 400] = "BAD_REQUEST";
4305
4317
  /**
4306
4318
  * Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated".
4307
4319
  * That is, the client must authenticate itself to get the requested response.
4308
4320
  */
4309
- HttpStatus[HttpStatus["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
4321
+ HttpStatusCodes[HttpStatusCodes["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
4310
4322
  /**
4311
4323
  * This response code is reserved for future use. The initial aim for creating this code was using
4312
4324
  * it for digital payment systems, however this status code is used very rarely and no standard convention exists.
4313
4325
  */
4314
- HttpStatus[HttpStatus["PAYMENT_REQUIRED"] = 402] = "PAYMENT_REQUIRED";
4326
+ HttpStatusCodes[HttpStatusCodes["PAYMENT_REQUIRED"] = 402] = "PAYMENT_REQUIRED";
4315
4327
  /**
4316
4328
  * The client does not have access rights to the content; that is, it is unauthorized,
4317
4329
  * so the server is refusing to give the requested resource. Unlike 401 Unauthorized,
4318
4330
  * the client's identity is known to the server.
4319
4331
  */
4320
- HttpStatus[HttpStatus["FORBIDDEN"] = 403] = "FORBIDDEN";
4332
+ HttpStatusCodes[HttpStatusCodes["FORBIDDEN"] = 403] = "FORBIDDEN";
4321
4333
  /**
4322
4334
  * The server can not find the requested resource. In the browser, this means the URL is not recognized.
4323
4335
  * In an API, this can also mean that the endpoint is valid but the resource itself does not exist.
@@ -4325,21 +4337,21 @@ var HttpStatus;
4325
4337
  * from an unauthorized client. This response code is probably the most well known due to its
4326
4338
  * frequent occurrence on the web.
4327
4339
  */
4328
- HttpStatus[HttpStatus["NOT_FOUND"] = 404] = "NOT_FOUND";
4340
+ HttpStatusCodes[HttpStatusCodes["NOT_FOUND"] = 404] = "NOT_FOUND";
4329
4341
  /**
4330
4342
  * The request method is known by the server but is not supported by the target resource.
4331
4343
  * For example, an API may not allow calling DELETE to remove a resource.
4332
4344
  */
4333
- HttpStatus[HttpStatus["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
4345
+ HttpStatusCodes[HttpStatusCodes["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
4334
4346
  /**
4335
4347
  * This response is sent when the web server, after performing server-driven content negotiation,
4336
4348
  * doesn't find any content that conforms to the criteria given by the user agent.
4337
4349
  */
4338
- HttpStatus[HttpStatus["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE";
4350
+ HttpStatusCodes[HttpStatusCodes["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE";
4339
4351
  /**
4340
4352
  * This is similar to 401 Unauthorized but authentication is needed to be done by a proxy.
4341
4353
  */
4342
- HttpStatus[HttpStatus["PROXY_AUTHENTICATION_REQUIRED"] = 407] = "PROXY_AUTHENTICATION_REQUIRED";
4354
+ HttpStatusCodes[HttpStatusCodes["PROXY_AUTHENTICATION_REQUIRED"] = 407] = "PROXY_AUTHENTICATION_REQUIRED";
4343
4355
  /**
4344
4356
  * This response is sent on an idle connection by some servers, even without any previous request by the client.
4345
4357
  * It means that the server would like to shut down this unused connection.
@@ -4347,107 +4359,107 @@ var HttpStatus;
4347
4359
  * like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing.
4348
4360
  * Also note that some servers merely shut down the connection without sending this message.
4349
4361
  */
4350
- HttpStatus[HttpStatus["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT";
4362
+ HttpStatusCodes[HttpStatusCodes["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT";
4351
4363
  /**
4352
4364
  * This response is sent when a request conflicts with the current state of the server.
4353
4365
  */
4354
- HttpStatus[HttpStatus["CONFLICT"] = 409] = "CONFLICT";
4366
+ HttpStatusCodes[HttpStatusCodes["CONFLICT"] = 409] = "CONFLICT";
4355
4367
  /**
4356
4368
  * This response is sent when the requested content has been permanently deleted from server,
4357
4369
  * with no forwarding address. Clients are expected to remove their caches and links to the resource.
4358
4370
  * The HTTP specification intends this status code to be used for "limited-time, promotional services".
4359
4371
  * APIs should not feel compelled to indicate resources that have been deleted with this status code.
4360
4372
  */
4361
- HttpStatus[HttpStatus["GONE"] = 410] = "GONE";
4373
+ HttpStatusCodes[HttpStatusCodes["GONE"] = 410] = "GONE";
4362
4374
  /**
4363
4375
  * Server rejected the request because the Content-Length header field is not defined and the server requires it.
4364
4376
  */
4365
- HttpStatus[HttpStatus["LENGTH_REQUIRED"] = 411] = "LENGTH_REQUIRED";
4377
+ HttpStatusCodes[HttpStatusCodes["LENGTH_REQUIRED"] = 411] = "LENGTH_REQUIRED";
4366
4378
  /**
4367
4379
  * The client has indicated preconditions in its headers which the server does not meet.
4368
4380
  */
4369
- HttpStatus[HttpStatus["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED";
4381
+ HttpStatusCodes[HttpStatusCodes["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED";
4370
4382
  /**
4371
4383
  * Request entity is larger than limits defined by server. The server might close the connection or
4372
4384
  * return an Retry-After header field.
4373
4385
  */
4374
- HttpStatus[HttpStatus["PAYLOAD_TOO_LARGE"] = 413] = "PAYLOAD_TOO_LARGE";
4386
+ HttpStatusCodes[HttpStatusCodes["PAYLOAD_TOO_LARGE"] = 413] = "PAYLOAD_TOO_LARGE";
4375
4387
  /**
4376
4388
  * The URI requested by the client is longer than the server is willing to interpret.
4377
4389
  */
4378
- HttpStatus[HttpStatus["URI_TOO_LONG"] = 414] = "URI_TOO_LONG";
4390
+ HttpStatusCodes[HttpStatusCodes["URI_TOO_LONG"] = 414] = "URI_TOO_LONG";
4379
4391
  /**
4380
4392
  * The media format of the requested data is not supported by the server, so the server is rejecting the request.
4381
4393
  */
4382
- HttpStatus[HttpStatus["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE";
4394
+ HttpStatusCodes[HttpStatusCodes["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE";
4383
4395
  /**
4384
4396
  * The range specified by the Range header field in the request cannot be fulfilled.
4385
4397
  * It's possible that the range is outside the size of the target URI's data.
4386
4398
  */
4387
- HttpStatus[HttpStatus["REQUESTED_RANGE_NOT_SATISFIABLE"] = 416] = "REQUESTED_RANGE_NOT_SATISFIABLE";
4399
+ HttpStatusCodes[HttpStatusCodes["REQUESTED_RANGE_NOT_SATISFIABLE"] = 416] = "REQUESTED_RANGE_NOT_SATISFIABLE";
4388
4400
  /**
4389
4401
  * This response code means the expectation indicated by the Expect request header field cannot be met by the server.
4390
4402
  */
4391
- HttpStatus[HttpStatus["EXPECTATION_FAILED"] = 417] = "EXPECTATION_FAILED";
4403
+ HttpStatusCodes[HttpStatusCodes["EXPECTATION_FAILED"] = 417] = "EXPECTATION_FAILED";
4392
4404
  /**
4393
4405
  * The server refuses the attempt to brew coffee with a teapot.
4394
4406
  */
4395
- HttpStatus[HttpStatus["I_AM_A_TEAPOT"] = 418] = "I_AM_A_TEAPOT";
4407
+ HttpStatusCodes[HttpStatusCodes["I_AM_A_TEAPOT"] = 418] = "I_AM_A_TEAPOT";
4396
4408
  /**
4397
4409
  * The request was directed at a server that is not able to produce a response.
4398
4410
  * This can be sent by a server that is not configured to produce responses for
4399
4411
  * the combination of scheme and authority that are included in the request URI.
4400
4412
  */
4401
- HttpStatus[HttpStatus["MISDIRECTED_REQUEST"] = 421] = "MISDIRECTED_REQUEST";
4413
+ HttpStatusCodes[HttpStatusCodes["MISDIRECTED_REQUEST"] = 421] = "MISDIRECTED_REQUEST";
4402
4414
  /**
4403
4415
  * The request was well-formed but was unable to be followed due to semantic errors.
4404
4416
  */
4405
- HttpStatus[HttpStatus["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY";
4417
+ HttpStatusCodes[HttpStatusCodes["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY";
4406
4418
  /**
4407
4419
  * The resource that is being accessed is locked.
4408
4420
  */
4409
- HttpStatus[HttpStatus["LOCKED"] = 423] = "LOCKED";
4421
+ HttpStatusCodes[HttpStatusCodes["LOCKED"] = 423] = "LOCKED";
4410
4422
  /**
4411
4423
  * The request failed due to failure of a previous request.
4412
4424
  */
4413
- HttpStatus[HttpStatus["FAILED_DEPENDENCY"] = 424] = "FAILED_DEPENDENCY";
4425
+ HttpStatusCodes[HttpStatusCodes["FAILED_DEPENDENCY"] = 424] = "FAILED_DEPENDENCY";
4414
4426
  /**
4415
4427
  * Indicates that the server is unwilling to risk processing a request that might be replayed.
4416
4428
  */
4417
- HttpStatus[HttpStatus["TOO_EARLY"] = 425] = "TOO_EARLY";
4429
+ HttpStatusCodes[HttpStatusCodes["TOO_EARLY"] = 425] = "TOO_EARLY";
4418
4430
  /**
4419
4431
  * The server refuses to perform the request using the current protocol but might be willing
4420
4432
  * to do so after the client upgrades to a different protocol. The server sends an Upgrade
4421
4433
  * header in a 426 response to indicate the required protocol(s).
4422
4434
  */
4423
- HttpStatus[HttpStatus["UPGRADE_REQUIRED"] = 428] = "UPGRADE_REQUIRED";
4435
+ HttpStatusCodes[HttpStatusCodes["UPGRADE_REQUIRED"] = 428] = "UPGRADE_REQUIRED";
4424
4436
  /**
4425
4437
  * The origin server requires the request to be conditional. This response is intended to prevent
4426
4438
  * the 'lost update' problem, where a client GETs a resource's state, modifies it and PUTs
4427
4439
  * it back to the server, when meanwhile a third party has modified the state on the server,
4428
4440
  * leading to a conflict.
4429
4441
  */
4430
- HttpStatus[HttpStatus["PRECONDITION_REQUIRED"] = 428] = "PRECONDITION_REQUIRED";
4442
+ HttpStatusCodes[HttpStatusCodes["PRECONDITION_REQUIRED"] = 428] = "PRECONDITION_REQUIRED";
4431
4443
  /**
4432
4444
  * The user has sent too many requests in a given amount of time ("rate limiting").
4433
4445
  */
4434
- HttpStatus[HttpStatus["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
4446
+ HttpStatusCodes[HttpStatusCodes["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
4435
4447
  /* *** Server error responses *** */
4436
4448
  /**
4437
4449
  * The server has encountered a situation it does not know how to handle.
4438
4450
  */
4439
- HttpStatus[HttpStatus["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
4451
+ HttpStatusCodes[HttpStatusCodes["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
4440
4452
  /**
4441
4453
  * The request method is not supported by the server and cannot be handled.
4442
4454
  * The only methods that servers are required to support (and therefore that must not return this code)
4443
4455
  * are GET and HEAD.
4444
4456
  */
4445
- HttpStatus[HttpStatus["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED";
4457
+ HttpStatusCodes[HttpStatusCodes["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED";
4446
4458
  /**
4447
4459
  * This error response means that the server, while working as a gateway to get
4448
4460
  * a response needed to handle the request, got an invalid response.
4449
4461
  */
4450
- HttpStatus[HttpStatus["BAD_GATEWAY"] = 502] = "BAD_GATEWAY";
4462
+ HttpStatusCodes[HttpStatusCodes["BAD_GATEWAY"] = 502] = "BAD_GATEWAY";
4451
4463
  /**
4452
4464
  * The server is not ready to handle the request. Common causes are a server that is down for maintenance
4453
4465
  * or that is overloaded. Note that together with this response, a user-friendly page explaining
@@ -4457,49 +4469,49 @@ var HttpStatus;
4457
4469
  * headers that are sent along with this response, as these temporary condition responses
4458
4470
  * should usually not be cached.
4459
4471
  */
4460
- HttpStatus[HttpStatus["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
4472
+ HttpStatusCodes[HttpStatusCodes["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
4461
4473
  /**
4462
4474
  * This error response is given when the server is acting as a gateway and cannot get a response in time.
4463
4475
  */
4464
- HttpStatus[HttpStatus["GATEWAY_TIMEOUT"] = 504] = "GATEWAY_TIMEOUT";
4476
+ HttpStatusCodes[HttpStatusCodes["GATEWAY_TIMEOUT"] = 504] = "GATEWAY_TIMEOUT";
4465
4477
  /**
4466
4478
  * The HTTP version used in the request is not supported by the server.
4467
4479
  */
4468
- HttpStatus[HttpStatus["HTTP_VERSION_NOT_SUPPORTED"] = 505] = "HTTP_VERSION_NOT_SUPPORTED";
4480
+ HttpStatusCodes[HttpStatusCodes["HTTP_VERSION_NOT_SUPPORTED"] = 505] = "HTTP_VERSION_NOT_SUPPORTED";
4469
4481
  /**
4470
4482
  * The server has an internal configuration error: the chosen variant resource is configured
4471
4483
  * to engage in transparent content negotiation itself, and is therefore not a proper end
4472
4484
  * point in the negotiation process.
4473
4485
  */
4474
- HttpStatus[HttpStatus["VARIANT_ALSO_NEGOTIATES"] = 506] = "VARIANT_ALSO_NEGOTIATES";
4486
+ HttpStatusCodes[HttpStatusCodes["VARIANT_ALSO_NEGOTIATES"] = 506] = "VARIANT_ALSO_NEGOTIATES";
4475
4487
  /**
4476
4488
  * The method could not be performed on the resource because the server is unable to store
4477
4489
  * the representation needed to successfully complete the request.
4478
4490
  */
4479
- HttpStatus[HttpStatus["INSUFFICIENT_STORAGE"] = 507] = "INSUFFICIENT_STORAGE";
4491
+ HttpStatusCodes[HttpStatusCodes["INSUFFICIENT_STORAGE"] = 507] = "INSUFFICIENT_STORAGE";
4480
4492
  /**
4481
4493
  * The server detected an infinite loop while processing the request.
4482
4494
  */
4483
- HttpStatus[HttpStatus["LOOP_DETECTED"] = 508] = "LOOP_DETECTED";
4495
+ HttpStatusCodes[HttpStatusCodes["LOOP_DETECTED"] = 508] = "LOOP_DETECTED";
4484
4496
  /**
4485
4497
  * Further extensions to the request are required for the server to fulfill it.
4486
4498
  */
4487
- HttpStatus[HttpStatus["NOT_EXTENDED"] = 510] = "NOT_EXTENDED";
4499
+ HttpStatusCodes[HttpStatusCodes["NOT_EXTENDED"] = 510] = "NOT_EXTENDED";
4488
4500
  /**
4489
4501
  * Indicates that the client needs to authenticate to gain network access.
4490
4502
  */
4491
- HttpStatus[HttpStatus["NETWORK_AUTHENTICATION_REQUIRED"] = 511] = "NETWORK_AUTHENTICATION_REQUIRED";
4492
- })(HttpStatus || (HttpStatus = {}));
4503
+ HttpStatusCodes[HttpStatusCodes["NETWORK_AUTHENTICATION_REQUIRED"] = 511] = "NETWORK_AUTHENTICATION_REQUIRED";
4504
+ })(HttpStatusCodes || (HttpStatusCodes = {}));
4493
4505
 
4494
- const knownKeys = Object.keys(HttpHeaders);
4495
- const knownKeysLower = knownKeys.map(x => x.toLowerCase());
4506
+ const knownKeys$1 = Object.keys(HttpHeaderCodes);
4507
+ const knownKeysLower$1 = knownKeys$1.map(x => x.toLowerCase());
4496
4508
  function normalizeHeaders(headers, normalCase) {
4497
4509
  if (!headers)
4498
4510
  return {};
4499
4511
  return Object.keys(headers).reduce((o, k) => {
4500
4512
  const v = headers[k];
4501
4513
  const key = normalCase
4502
- ? knownKeys[knownKeysLower.indexOf(k.toLowerCase())] || camelize(k) :
4514
+ ? knownKeys$1[knownKeysLower$1.indexOf(k.toLowerCase())] || camelize(k) :
4503
4515
  k.toLowerCase();
4504
4516
  if (k.toLowerCase() === 'set-cookie')
4505
4517
  o[key] = Array.isArray(v) ? v : [v];
@@ -4542,11 +4554,11 @@ class BatchMultipart {
4542
4554
  addRequestPart(content, part) {
4543
4555
  const headers = {
4544
4556
  ...normalizeHeaders(part?.headers || {}, true),
4545
- [HttpHeaders.Content_Type]: 'application/http',
4546
- [HttpHeaders.Content_Transfer_Encoding]: 'binary'
4557
+ [HttpHeaderCodes.Content_Type]: 'application/http',
4558
+ [HttpHeaderCodes.Content_Transfer_Encoding]: 'binary'
4547
4559
  };
4548
4560
  if (part?.contentId)
4549
- headers[HttpHeaders.Content_ID] = part.contentId;
4561
+ headers[HttpHeaderCodes.Content_ID] = part.contentId;
4550
4562
  this._parts.push({
4551
4563
  headers,
4552
4564
  contentId: part?.contentId,
@@ -4557,11 +4569,11 @@ class BatchMultipart {
4557
4569
  addHttpResponse(content, part) {
4558
4570
  const headers = {
4559
4571
  ...normalizeHeaders(part?.headers || {}, true),
4560
- [HttpHeaders.Content_Type]: 'application/http',
4561
- [HttpHeaders.Content_Transfer_Encoding]: 'binary'
4572
+ [HttpHeaderCodes.Content_Type]: 'application/http',
4573
+ [HttpHeaderCodes.Content_Transfer_Encoding]: 'binary'
4562
4574
  };
4563
4575
  if (part?.contentId)
4564
- headers[HttpHeaders.Content_ID] = part.contentId;
4576
+ headers[HttpHeaderCodes.Content_ID] = part.contentId;
4565
4577
  this._parts.push({
4566
4578
  headers,
4567
4579
  contentId: part?.contentId,
@@ -4572,11 +4584,11 @@ class BatchMultipart {
4572
4584
  addBatch(batch, part) {
4573
4585
  const headers = {
4574
4586
  ...normalizeHeaders(part?.headers || {}, true),
4575
- [HttpHeaders.Content_Type]: 'application/http',
4576
- [HttpHeaders.Content_Transfer_Encoding]: 'binary'
4587
+ [HttpHeaderCodes.Content_Type]: 'application/http',
4588
+ [HttpHeaderCodes.Content_Transfer_Encoding]: 'binary'
4577
4589
  };
4578
4590
  if (part?.contentId)
4579
- headers[HttpHeaders.Content_ID] = part.contentId;
4591
+ headers[HttpHeaderCodes.Content_ID] = part.contentId;
4580
4592
  this._parts.push({
4581
4593
  headers,
4582
4594
  contentId: part?.contentId,
@@ -4648,7 +4660,7 @@ class BatchMultipart {
4648
4660
  if (part.content instanceof HttpRequestContent)
4649
4661
  s += (part.content.method || 'GET').toUpperCase() + ' ' + part.content.url + ' HTTP/1.1' + CRLF;
4650
4662
  else
4651
- s += 'HTTP/1.1 ' + part.content.status + (HttpStatus[part.content.status] || 'Unknown') + CRLF;
4663
+ s += 'HTTP/1.1 ' + part.content.status + (HttpStatusCodes[part.content.status] || 'Unknown') + CRLF;
4652
4664
  if (part.content.headers) {
4653
4665
  for (const [k, v] of Object.entries(part.content.headers)) {
4654
4666
  if (v === '' || v == null)
@@ -4880,45 +4892,58 @@ function OprSearchResolver(options) {
4880
4892
  };
4881
4893
  }
4882
4894
 
4895
+ var _a$4, _b$2, _c$1, _d;
4896
+ function isMap(v) {
4897
+ return v && typeof v.forEach === 'function';
4898
+ }
4899
+ const kKeyMap = Symbol('kKeyMap');
4900
+ const kKeyOrder = Symbol('kKeyOrder');
4901
+ const kWellKnownKeys = Symbol('kWellKnownKeys');
4902
+ const kOptions$3 = Symbol('kOptions');
4903
+ /**
4904
+ * A Map implementation that supports case-insensitivity and ordered keys
4905
+ */
4883
4906
  class ResponsiveMap extends Map {
4884
- constructor(data, wellKnownKeys) {
4907
+ constructor(init, options) {
4885
4908
  super();
4886
- this._keyMap = new Map();
4887
- this._keyOrder = [];
4888
- this._wellKnownKeyMap = new Map();
4889
- if (wellKnownKeys)
4890
- wellKnownKeys.forEach(k => this._wellKnownKeyMap.set(k.toLowerCase(), k));
4891
- if (typeof data?.forEach === 'function') {
4892
- data.forEach((v, k) => this.set(k, v));
4893
- }
4894
- else if (data && typeof data === 'object')
4895
- Object.keys(data).forEach(k => this.set(k, data[k]));
4909
+ this[_a$4] = new Map();
4910
+ this[_b$2] = [];
4911
+ this[_c$1] = new Map();
4912
+ this[_d] = { caseSensitive: false };
4913
+ this[kOptions$3].caseSensitive = !!options?.caseSensitive;
4914
+ if (options?.wellKnownKeys)
4915
+ options.wellKnownKeys.forEach(k => this[kWellKnownKeys].set(k.toLowerCase(), k));
4916
+ if (isMap(init)) {
4917
+ init.forEach((v, k) => this.set(k, v));
4918
+ }
4919
+ else if (init && typeof init === 'object')
4920
+ Object.keys(init).forEach(k => this.set(k, init[k]));
4896
4921
  }
4897
4922
  clear() {
4898
4923
  super.clear();
4899
- this._keyMap.clear();
4900
- this._keyOrder = [];
4924
+ this[kKeyMap].clear();
4925
+ this[kKeyOrder] = [];
4901
4926
  }
4902
4927
  get(key) {
4903
4928
  const orgKey = this._getOriginalKey(key);
4904
4929
  return super.get(orgKey);
4905
4930
  }
4906
4931
  has(key) {
4907
- return this._keyMap.has(this._getLowerKey(key));
4932
+ return this[kKeyMap].has(this._getStoringKey(key));
4908
4933
  }
4909
4934
  set(key, value) {
4910
4935
  key = this._getOriginalKey(key);
4911
- this._keyMap.set(this._getLowerKey(key), key);
4912
- if (!this._keyOrder.includes(key))
4913
- this._keyOrder.push(key);
4936
+ this[kKeyMap].set(this._getStoringKey(key), key);
4937
+ if (!this[kKeyOrder].includes(key))
4938
+ this[kKeyOrder].push(key);
4914
4939
  return super.set(key, value);
4915
4940
  }
4916
4941
  keys() {
4917
- return this._keyOrder.values();
4942
+ return this[kKeyOrder].values();
4918
4943
  }
4919
4944
  values() {
4920
4945
  let i = -1;
4921
- const arr = this._keyOrder;
4946
+ const arr = this[kKeyOrder];
4922
4947
  const map = this;
4923
4948
  return {
4924
4949
  [Symbol.iterator]() {
@@ -4935,7 +4960,7 @@ class ResponsiveMap extends Map {
4935
4960
  }
4936
4961
  entries() {
4937
4962
  let i = -1;
4938
- const arr = this._keyOrder;
4963
+ const arr = this[kKeyOrder];
4939
4964
  const map = this;
4940
4965
  return {
4941
4966
  [Symbol.iterator]() {
@@ -4952,27 +4977,31 @@ class ResponsiveMap extends Map {
4952
4977
  }
4953
4978
  delete(key) {
4954
4979
  const orgKey = this._getOriginalKey(key);
4955
- const k = this._getLowerKey(key);
4956
- this._keyMap.delete(k);
4957
- const i = this._keyOrder.indexOf(orgKey);
4980
+ const k = this._getStoringKey(key);
4981
+ this[kKeyMap].delete(k);
4982
+ const i = this[kKeyOrder].indexOf(orgKey);
4958
4983
  if (i >= 0)
4959
- this._keyOrder.splice(i, 1);
4984
+ this[kKeyOrder].splice(i, 1);
4960
4985
  return super.delete(orgKey);
4961
4986
  }
4962
4987
  sort(compareFn) {
4963
- this._keyOrder.sort(compareFn);
4988
+ this[kKeyOrder].sort(compareFn);
4964
4989
  return this;
4965
4990
  }
4966
- [Symbol.iterator]() {
4991
+ [(_a$4 = kKeyMap, _b$2 = kKeyOrder, _c$1 = kWellKnownKeys, _d = kOptions$3, Symbol.iterator)]() {
4967
4992
  return this.entries();
4968
4993
  }
4969
4994
  _getOriginalKey(key) {
4995
+ if (this[kOptions$3].caseSensitive)
4996
+ return key;
4970
4997
  if (typeof key === 'string')
4971
- return this._keyMap.get(key.toLowerCase()) ??
4972
- (this._wellKnownKeyMap.get(key.toLowerCase()) ?? key);
4998
+ return this[kKeyMap].get(key.toLowerCase()) ??
4999
+ (this[kWellKnownKeys].get(key.toLowerCase()) ?? key);
4973
5000
  return key;
4974
5001
  }
4975
- _getLowerKey(key) {
5002
+ _getStoringKey(key) {
5003
+ if (this[kOptions$3].caseSensitive)
5004
+ return key;
4976
5005
  if (typeof key === 'string')
4977
5006
  return key.toLowerCase();
4978
5007
  return key;
@@ -5725,6 +5754,9 @@ class CollectionResourceInfo extends ResourceInfo {
5725
5754
  metadata.search.sortFields = normalizeFieldArray(document, dataType, metadata.search.sortFields);
5726
5755
  }
5727
5756
  }
5757
+ get instance() {
5758
+ return this.metadata.instance;
5759
+ }
5728
5760
  get keyFields() {
5729
5761
  return this.metadata.keyFields;
5730
5762
  }
@@ -5752,6 +5784,10 @@ class CollectionResourceInfo extends ResourceInfo {
5752
5784
  get search() {
5753
5785
  return this.metadata.search;
5754
5786
  }
5787
+ getHandler(method) {
5788
+ const r = this.metadata[method];
5789
+ return r && r.handler;
5790
+ }
5755
5791
  getSchema(jsonOnly) {
5756
5792
  const out = super.getSchema(jsonOnly);
5757
5793
  if (out.keyFields.length < 2)
@@ -5823,25 +5859,25 @@ class OpraDocument {
5823
5859
  const t = this.types.get(name);
5824
5860
  if (t)
5825
5861
  return t;
5826
- throw new Error(`Data type "${name}" does not exists`);
5862
+ throw new NotFoundError(`Data type "${name}" does not exists`);
5827
5863
  }
5828
5864
  getComplexDataType(name) {
5829
5865
  const t = this.getDataType(name);
5830
5866
  if (t && t instanceof ComplexType)
5831
5867
  return t;
5832
- throw new Error(`Data type "${name}" is not a ComplexType`);
5868
+ throw new NotAcceptableError(`Data type "${name}" is not a ComplexType`);
5833
5869
  }
5834
5870
  getSimpleDataType(name) {
5835
5871
  const t = this.getDataType(name);
5836
5872
  if (t && t instanceof SimpleType)
5837
5873
  return t;
5838
- throw new Error(`Data type "${name}" is not a SimpleType`);
5874
+ throw new NotAcceptableError(`Data type "${name}" is not a SimpleType`);
5839
5875
  }
5840
5876
  getUnionDataType(name) {
5841
5877
  const t = this.getDataType(name);
5842
5878
  if (t && t instanceof UnionType)
5843
5879
  return t;
5844
- throw new Error(`Data type "${name}" is not a UnionType`);
5880
+ throw new NotAcceptableError(`Data type "${name}" is not a UnionType`);
5845
5881
  }
5846
5882
  get resources() {
5847
5883
  return this._resources;
@@ -5852,19 +5888,19 @@ class OpraDocument {
5852
5888
  getResource(name) {
5853
5889
  const t = this.resources.get(name);
5854
5890
  if (!t)
5855
- throw new Error(`Resource "${name}" does not exists`);
5891
+ throw new NotFoundError(`Resource "${name}" does not exists`);
5856
5892
  return t;
5857
5893
  }
5858
5894
  getCollectionResource(name) {
5859
5895
  const t = this.getResource(name);
5860
5896
  if (!(t instanceof CollectionResourceInfo))
5861
- throw new Error(`"${name}" is not a CollectionResource`);
5897
+ throw new NotAcceptableError(`"${name}" is not a CollectionResource`);
5862
5898
  return t;
5863
5899
  }
5864
5900
  getSingletonResource(name) {
5865
5901
  const t = this.getResource(name);
5866
5902
  if (!(t instanceof SingletonResourceInfo))
5867
- throw new Error(`"${name}" is not a SingletonResource`);
5903
+ throw new NotAcceptableError(`"${name}" is not a SingletonResource`);
5868
5904
  return t;
5869
5905
  }
5870
5906
  getMetadata(jsonOnly) {
@@ -5905,7 +5941,7 @@ class OpraDocument {
5905
5941
  dataType = new UnionType(this, name, { ...schema, types: [] });
5906
5942
  }
5907
5943
  else
5908
- throw new TypeError(`Invalid data type schema`);
5944
+ throw new InternalServerError(`Invalid data type schema`);
5909
5945
  this._types.set(name, dataType);
5910
5946
  if (isOwn)
5911
5947
  this._ownTypes.set(name, dataType);
@@ -5915,16 +5951,16 @@ class OpraDocument {
5915
5951
  if (OpraSchema.isCollectionResource(schema) || OpraSchema.isSingletonResource(schema)) {
5916
5952
  const dataType = this.getDataType(schema.type);
5917
5953
  if (!dataType)
5918
- throw new TypeError(`Datatype "${schema.type}" declared in CollectionResource (${name}) does not exists`);
5954
+ throw new InternalServerError(`Datatype "${schema.type}" declared in CollectionResource (${name}) does not exists`);
5919
5955
  if (!(dataType instanceof ComplexType))
5920
- throw new TypeError(`${schema.type} is not an ComplexType`);
5956
+ throw new InternalServerError(`${schema.type} is not an ComplexType`);
5921
5957
  if (OpraSchema.isCollectionResource(schema))
5922
5958
  this.resources.set(name, new CollectionResourceInfo(this, name, dataType, schema));
5923
5959
  else
5924
5960
  this.resources.set(name, new SingletonResourceInfo(this, name, dataType, schema));
5925
5961
  }
5926
5962
  else
5927
- throw new TypeError(`Unknown resource kind (${schema.kind})`);
5963
+ throw new InternalServerError(`Unknown resource kind (${schema.kind})`);
5928
5964
  }
5929
5965
  _initTypes() {
5930
5966
  for (const dataType of this._types.values()) {
@@ -6445,51 +6481,42 @@ class OpraURLPathComponent {
6445
6481
  }
6446
6482
  }
6447
6483
 
6484
+ var _a$3;
6448
6485
  const nodeInspectCustom$2 = Symbol.for('nodejs.util.inspect.custom');
6449
- class OpraURLPath extends EventEmitter {
6450
- constructor(...args) {
6451
- super();
6452
- this._entries = [];
6453
- for (const x of args) {
6454
- if (isURL(x)) {
6455
- this._parse(x.pathname);
6456
- continue;
6457
- }
6458
- // noinspection SuspiciousTypeOfGuard
6459
- if (x instanceof OpraURLPath)
6460
- this._entries.push(...x._entries);
6461
- else
6462
- this.add(x);
6463
- }
6486
+ const kEntries$2 = Symbol('kEntries');
6487
+ const kOptions$2 = Symbol('kOptions');
6488
+ class OpraURLPath {
6489
+ constructor(init, options) {
6490
+ this[_a$3] = [];
6491
+ this[kOptions$2] = { ...options, onChange: undefined };
6492
+ if (Array.isArray(init))
6493
+ this.join(...init);
6494
+ else if (init)
6495
+ this.join(init);
6496
+ this[kOptions$2].onChange = options?.onChange;
6464
6497
  }
6465
6498
  get size() {
6466
- return this._entries.length;
6499
+ return this[kEntries$2].length;
6467
6500
  }
6468
- add(component, key, typeCast) {
6469
- this._add(component, key, typeCast);
6470
- this.emit('change');
6501
+ changed() {
6502
+ if (this[kOptions$2].onChange)
6503
+ this[kOptions$2].onChange();
6471
6504
  }
6472
6505
  clear() {
6473
- this._entries = [];
6474
- this.emit('change');
6506
+ this[kEntries$2] = [];
6507
+ this.changed();
6475
6508
  }
6476
6509
  get(index) {
6477
- return this._entries[index];
6510
+ return this[kEntries$2][index];
6478
6511
  }
6479
- join(pathString) {
6480
- const pathTokenizer = tokenize(normalizePath(pathString, true), {
6481
- delimiters: '/', quotes: true, brackets: true,
6482
- });
6483
- for (const x of pathTokenizer) {
6484
- const p = decodePathComponent(x);
6485
- this._add(p);
6486
- }
6487
- this.emit('change');
6512
+ join(...source) {
6513
+ source.forEach(x => this._join(this[kEntries$2], x));
6514
+ this.changed();
6488
6515
  return this;
6489
6516
  }
6490
6517
  entries() {
6491
6518
  let i = -1;
6492
- const arr = [...this._entries];
6519
+ const arr = [...this[kEntries$2]];
6493
6520
  return {
6494
6521
  [Symbol.iterator]() {
6495
6522
  return this;
@@ -6503,9 +6530,46 @@ class OpraURLPath extends EventEmitter {
6503
6530
  }
6504
6531
  };
6505
6532
  }
6533
+ forEach(callback) {
6534
+ for (const item of this[kEntries$2]) {
6535
+ callback.call(this, item, this);
6536
+ }
6537
+ }
6538
+ getResource(index) {
6539
+ const v = this[kEntries$2][index];
6540
+ return v == null ? undefined : v.resource;
6541
+ }
6542
+ getKey(index) {
6543
+ const v = this[kEntries$2][index];
6544
+ return v == null ? undefined : v.key;
6545
+ }
6546
+ pop() {
6547
+ const out = this[kEntries$2].pop();
6548
+ this.changed();
6549
+ return out;
6550
+ }
6551
+ shift() {
6552
+ const out = this[kEntries$2].shift();
6553
+ this.changed();
6554
+ return out;
6555
+ }
6556
+ slice(start, end) {
6557
+ return new OpraURLPath(this[kEntries$2].slice(start, end));
6558
+ }
6559
+ splice(start, deleteCount, join) {
6560
+ const items = (join ? this._join([], join) : []);
6561
+ this[kEntries$2].splice(start, deleteCount, ...items);
6562
+ this.changed();
6563
+ }
6564
+ unshift(join) {
6565
+ return this.splice(0, 0, join);
6566
+ }
6567
+ toString() {
6568
+ return this[kEntries$2].map(x => encodePathComponent(x.resource, x.key, x.typeCast)).join('/');
6569
+ }
6506
6570
  values() {
6507
6571
  let i = -1;
6508
- const arr = [...this._entries];
6572
+ const arr = [...this[kEntries$2]];
6509
6573
  return {
6510
6574
  [Symbol.iterator]() {
6511
6575
  return this;
@@ -6519,59 +6583,56 @@ class OpraURLPath extends EventEmitter {
6519
6583
  }
6520
6584
  };
6521
6585
  }
6522
- forEach(callback) {
6523
- for (const item of this._entries) {
6524
- callback.call(this, item.resource, item.key, this);
6586
+ _join(target, source) {
6587
+ if (typeof source === 'string') {
6588
+ const pathTokenizer = tokenize(normalizePath(source, true), {
6589
+ delimiters: '/', quotes: true, brackets: true,
6590
+ });
6591
+ for (const x of pathTokenizer) {
6592
+ const p = decodePathComponent(x);
6593
+ target.push(new OpraURLPathComponent(p));
6594
+ }
6595
+ return;
6525
6596
  }
6597
+ if (source instanceof OpraURLPath) {
6598
+ target.push(...source[kEntries$2].map(x => new OpraURLPathComponent(x)));
6599
+ return;
6600
+ }
6601
+ if (typeof source === 'object' && source.path instanceof OpraURLPath) {
6602
+ this._join(target, source.path);
6603
+ return;
6604
+ }
6605
+ if (isURL(source)) {
6606
+ this._join(target, source.pathname);
6607
+ return;
6608
+ }
6609
+ if (Array.isArray(source)) {
6610
+ source.forEach(x => this._join(target, x));
6611
+ return;
6612
+ }
6613
+ target.push(new OpraURLPathComponent(source));
6526
6614
  }
6527
- getResource(index) {
6528
- const v = this._entries[index];
6529
- return v == null ? undefined : v.resource;
6530
- }
6531
- getKey(index) {
6532
- const v = this._entries[index];
6533
- return v == null ? undefined : v.key;
6534
- }
6535
- toString() {
6536
- return this._entries.map(x => encodePathComponent(x.resource, x.key, x.typeCast)).join('/');
6615
+ /* istanbul ignore next */
6616
+ [(_a$3 = kEntries$2, nodeInspectCustom$2)]() {
6617
+ return this[kEntries$2];
6537
6618
  }
6538
6619
  [Symbol.iterator]() {
6539
6620
  return this.entries();
6540
6621
  }
6541
- /* istanbul ignore next */
6542
- [nodeInspectCustom$2]() {
6543
- return this._entries;
6544
- }
6545
- _add(component, key, typeCast) {
6546
- if (component instanceof OpraURLPathComponent) {
6547
- this._entries.push(component);
6548
- }
6549
- else if (typeof component === 'object')
6550
- this._entries.push(new OpraURLPathComponent(component));
6551
- else
6552
- this._entries.push(new OpraURLPathComponent({ resource: component, key, typeCast }));
6553
- }
6554
- _parse(v) {
6555
- if (!v)
6556
- return;
6557
- const pathTokenizer = tokenize(v, { delimiters: '/', quotes: true, brackets: true });
6558
- for (const x of pathTokenizer) {
6559
- if (!x)
6560
- continue;
6561
- const p = decodePathComponent(x);
6562
- this._add(p);
6563
- }
6564
- this.emit('change');
6622
+ get [Symbol.toStringTag]() {
6623
+ return 'OpraURLPath';
6565
6624
  }
6566
6625
  }
6626
+ OpraURLPath.kEntries = kEntries$2;
6627
+ OpraURLPath.kOptions = kOptions$2;
6567
6628
 
6568
- class Format {
6629
+ class HttpParamCodec {
6569
6630
  }
6570
6631
 
6571
6632
  const trueValues = ['true', 't', 'yes', 'y', '1'];
6572
6633
  const falseValues = ['false', 'f', 'no', 'n', '0'];
6573
- class BooleanFormat extends Format {
6574
- parse(value) {
6634
+ class BooleanCodec extends HttpParamCodec {
6635
+ decode(value) {
6575
6636
  if (value === '')
6576
6637
  return true;
6577
6638
  // noinspection SuspiciousTypeOfGuard
@@ -6583,7 +6644,7 @@ class BooleanFormat extends Format {
6583
6644
  return false;
6584
6645
  throw new TypeError(`"${value}" is not a valid boolean`);
6585
6646
  }
6586
- stringify(value) {
6647
+ encode(value) {
6587
6648
  return typeof value === 'boolean' ?
6588
6649
  (value ? 'true' : 'false') : '';
6589
6650
  }
@@ -6592,7 +6653,7 @@ class BooleanFormat extends Format {
6592
6653
  /* eslint-disable max-len */
6593
6654
  // noinspection RegExpUnnecessaryNonCapturingGroup
6594
6655
  const DATE_FORMAT_PATTERN = /^(\d{4})(?:-?(0[1-9]|1[012])(?:-?([123]0|[012][1-9]|31))?)?(?:[T ]?([01][0-9]|2[0-3]):?([0-5][0-9]):?([0-5][0-9])?(?:\.(\d+))?(?:(Z)|(?:([+-])([01]?[0-9]|2[0-3]):?([0-5][0-9])?))?)?$/;
6595
- class DateFormat extends Format {
6656
+ class DateCodec extends HttpParamCodec {
6596
6657
  constructor(options) {
6597
6658
  super();
6598
6659
  this.max = options?.max ? coerceToDateString(options.max) : undefined;
@@ -6600,7 +6661,7 @@ class DateFormat extends Format {
6600
6661
  this.time = options?.time ?? true;
6601
6662
  this.timeZone = options?.timeZone ?? true;
6602
6663
  }
6603
- parse(value) {
6664
+ decode(value) {
6604
6665
  const v = coerceToDateString(value, this.time, this.timeZone);
6605
6666
  if (this.min != null && v < this.min)
6606
6667
  throw new TypeError(`Value must be ${this.min} or greater.`);
@@ -6608,7 +6669,7 @@ class DateFormat extends Format {
6608
6669
  throw new TypeError(`Value must be ${this.max} or less.`);
6609
6670
  return v;
6610
6671
  }
6611
- stringify(value) {
6672
+ encode(value) {
6612
6673
  return coerceToDateString(value, this.time, this.timeZone);
6613
6674
  }
6614
6675
  }
@@ -6629,25 +6690,25 @@ function coerceToDateString(value, time, timeZone) {
6629
6690
  return v;
6630
6691
  }
6631
6692
 
6632
- class FilterFormat extends Format {
6633
- parse(value) {
6693
+ class FilterCodec extends HttpParamCodec {
6694
+ decode(value) {
6634
6695
  if (value instanceof Expression)
6635
6696
  return value;
6636
6697
  return parseFilter(value);
6637
6698
  }
6638
- stringify(value) {
6699
+ encode(value) {
6639
6700
  // @ts-ignore
6640
6701
  return value ? '' + value : '';
6641
6702
  }
6642
6703
  }
6643
6704
 
6644
- class NumberFormat extends Format {
6705
+ class NumberCodec extends HttpParamCodec {
6645
6706
  constructor(options) {
6646
6707
  super();
6647
6708
  this.max = options?.max;
6648
6709
  this.min = options?.min;
6649
6710
  }
6650
- parse(value) {
6711
+ decode(value) {
6651
6712
  // noinspection SuspiciousTypeOfGuard
6652
6713
  const v = typeof value === 'number' ? value : parseFloat(value);
6653
6714
  if (isNaN(v))
@@ -6658,18 +6719,18 @@ class NumberFormat extends Format {
6658
6719
  throw new TypeError(`Value must be ${this.max} or less.`);
6659
6720
  return v;
6660
6721
  }
6661
- stringify(value) {
6722
+ encode(value) {
6662
6723
  return typeof value === 'number' ? '' + value : '';
6663
6724
  }
6664
6725
  }
6665
6726
 
6666
- class IntegerFormat extends NumberFormat {
6727
+ class IntegerCodec extends NumberCodec {
6667
6728
  constructor(options) {
6668
6729
  super(options);
6669
6730
  this.enum = options?.enum;
6670
6731
  }
6671
- parse(value) {
6672
- const v = super.parse(value);
6732
+ decode(value) {
6733
+ const v = super.decode(value);
6673
6734
  if (!Number.isInteger(v))
6674
6735
  throw new TypeError(`"${value}" is not a valid integer`);
6675
6736
  if (this.enum && !this.enum.includes(v))
@@ -6678,14 +6739,14 @@ class IntegerFormat extends NumberFormat {
6678
6739
  }
6679
6740
  }
6680
6741
 
6681
- class StringFormat extends Format {
6742
+ class StringCodec extends HttpParamCodec {
6682
6743
  constructor(options) {
6683
6744
  super();
6684
6745
  this.maxLength = options?.maxLength;
6685
6746
  this.minLength = options?.minLength;
6686
6747
  this.enum = options?.enum;
6687
6748
  }
6688
- parse(value) {
6749
+ decode(value) {
6689
6750
  if (this.minLength != null && value.length < this.minLength)
6690
6751
  throw new TypeError(`Value must be at least ${this.minLength} character${this.minLength > 1 ? 's' : ''} long.`);
6691
6752
  if (this.maxLength != null && value.length > this.maxLength)
@@ -6694,406 +6755,588 @@ class StringFormat extends Format {
6694
6755
  throw new TypeError(`"${value}" is not one of allowed enum values (${this.enum}).`);
6695
6756
  return value;
6696
6757
  }
6697
- stringify(value) {
6758
+ encode(value) {
6698
6759
  return value == null ? '' : '' + value;
6699
6760
  }
6700
6761
  }
6701
6762
 
6702
- const internalFormats = {
6703
- 'integer': new IntegerFormat(),
6704
- 'number': new NumberFormat(),
6705
- 'string': new StringFormat(),
6706
- 'boolean': new BooleanFormat(),
6707
- 'date': new DateFormat(),
6708
- 'filter': new FilterFormat()
6763
+ /**
6764
+ * Encode input string with standard encodeURIComponent and then un-encode specific characters.
6765
+ */
6766
+ const ENCODING_REGEX = /%(\d[a-f0-9])/gi;
6767
+ const ENCODING_REPLACEMENTS = {
6768
+ '2C': ',',
6769
+ '2F': '/',
6770
+ '24': '$',
6771
+ '3A': ':',
6772
+ '3B': ';',
6773
+ '3D': '=',
6774
+ '3F': '?',
6775
+ '40': '@'
6709
6776
  };
6710
- const nodeInspectCustom$1 = Symbol.for('nodejs.util.inspect.custom');
6711
- class OpraURLSearchParams extends EventEmitter {
6712
- constructor(init) {
6713
- super();
6714
- this._params = new ResponsiveMap();
6715
- this._entries = new ResponsiveMap();
6716
- this._size = 0;
6717
- this.defineParam('$filter', { format: 'filter' });
6718
- this.defineParam('$limit', { format: new IntegerFormat({ min: 0 }) });
6719
- this.defineParam('$skip', { format: new IntegerFormat({ min: 0 }) });
6720
- this.defineParam('$pick', { format: 'string', array: 'strict' });
6721
- this.defineParam('$omit', { format: 'string', array: 'strict' });
6722
- this.defineParam('$include', { format: 'string', array: 'strict' });
6723
- this.defineParam('$sort', { format: 'string', array: 'strict' });
6724
- this.defineParam('$distinct', { format: 'boolean' });
6725
- this.defineParam('$count', { format: 'boolean' });
6726
- if (init) {
6727
- if (typeof init === 'string')
6728
- this.parse(init);
6729
- else
6730
- this.addAll(init);
6731
- }
6777
+ function encodeURIParam(v) {
6778
+ return encodeURIComponent(v).replace(ENCODING_REGEX, (s, t) => ENCODING_REPLACEMENTS[t] ?? s);
6779
+ }
6780
+
6781
+ var _a$2, _b$1, _c;
6782
+ const kEntries$1 = Symbol('kEntries');
6783
+ const kSize$1 = Symbol('kSize');
6784
+ const kParamDefs = Symbol('kParamDefs');
6785
+ const kOptions$1 = Symbol('kOptions');
6786
+ const defaultKeyDecoder = (s) => decodeURIComponent(s);
6787
+ const defaultValueDecoder = (s) => decodeURIComponent(s);
6788
+ const defaultKeyEncoder = (s) => encodeURIParam(s);
6789
+ const defaultValueEncoder = (s) => encodeURIParam(s);
6790
+ const internalCodecs = {
6791
+ 'boolean': new BooleanCodec(),
6792
+ 'date': new DateCodec(),
6793
+ 'filter': new FilterCodec(),
6794
+ 'integer': new IntegerCodec(),
6795
+ 'number': new NumberCodec(),
6796
+ 'string': new StringCodec()
6797
+ };
6798
+ class HttpParams {
6799
+ constructor(init, options) {
6800
+ this[_a$2] = new ResponsiveMap();
6801
+ this[_b$1] = 0;
6802
+ this[_c] = new Map();
6803
+ this[kOptions$1] = { ...options, onChange: undefined };
6804
+ const defineParams = options?.params;
6805
+ if (defineParams)
6806
+ Object.keys(defineParams).forEach(key => this.define(key, defineParams[key]));
6807
+ if (init)
6808
+ this.appendAll(init);
6809
+ this[kOptions$1].onChange = options?.onChange;
6732
6810
  }
6733
6811
  get size() {
6734
- return this._size;
6812
+ return this[kSize$1];
6735
6813
  }
6736
- addAll(values) {
6737
- let changed = false;
6738
- if (typeof values.forEach === 'function') {
6739
- values.forEach((value, name) => {
6740
- changed = this._add(name, value) || changed;
6741
- });
6814
+ /**
6815
+ * Appends a new value to the existing set of values for a parameter
6816
+ * and returns this instance
6817
+ */
6818
+ append(name, value) {
6819
+ this._append(name, value);
6820
+ this.changed();
6821
+ return this;
6822
+ }
6823
+ appendAll(input) {
6824
+ if (typeof input === 'string') {
6825
+ if (input && input.startsWith('?'))
6826
+ input = input.substring(1);
6827
+ if (!input)
6828
+ return this;
6829
+ const tokenizer = tokenize(input, { delimiters: '&', quotes: true, brackets: true });
6830
+ for (const token of tokenizer) {
6831
+ if (!token)
6832
+ continue;
6833
+ const itemTokenizer = tokenize(token, {
6834
+ delimiters: '=',
6835
+ quotes: true,
6836
+ brackets: true
6837
+ });
6838
+ const k = this.decodeKey(itemTokenizer.next() || '');
6839
+ const v = this.decodeValue(itemTokenizer.join('='), k);
6840
+ this._append(k, v);
6841
+ }
6742
6842
  }
6743
- else if (typeof values === 'object') ;
6843
+ else if (input.forEach && typeof input.forEach === 'function')
6844
+ input.forEach((value, name) => this._append(name, value));
6744
6845
  else
6745
- throw new TypeError(`Invalid argument`);
6746
- if (changed)
6747
- this.emit('change');
6846
+ Object.keys(input).forEach(name => this._append(name, input[name]));
6847
+ return this;
6748
6848
  }
6749
- append(name, value) {
6750
- if (this._add(name, value))
6751
- this.emit('change');
6849
+ changed() {
6850
+ if (this[kOptions$1].onChange)
6851
+ this[kOptions$1].onChange();
6752
6852
  }
6753
6853
  clear() {
6754
- this._entries.clear();
6755
- this._size = 0;
6756
- this.emit('change');
6854
+ if (this[kEntries$1].size) {
6855
+ this[kEntries$1].clear();
6856
+ this[kSize$1] = 0;
6857
+ this.changed();
6858
+ }
6757
6859
  }
6758
- defineParam(name, options) {
6759
- if (!name)
6760
- throw new Error('Parameter name required');
6761
- const meta = {
6762
- ...options,
6763
- name,
6764
- format: options?.format || 'string'
6765
- };
6766
- if (typeof meta.format === 'string' && !internalFormats[meta.format])
6767
- throw new Error(`Unknown data format "${meta.format}"`);
6768
- meta.format = meta.format || 'string';
6769
- this._params.set(name, meta);
6860
+ /**
6861
+ * Deletes values for a given parameter
6862
+ */
6863
+ delete(name, value) {
6864
+ if (this._delete(name, value))
6865
+ this.changed();
6770
6866
  return this;
6771
6867
  }
6772
- delete(name) {
6773
- if (this._delete(name))
6774
- this.emit('change');
6775
- }
6868
+ /**
6869
+ * Returns an iterable of key, value pairs for every entry in the map.
6870
+ */
6776
6871
  entries() {
6777
- const items = [];
6778
- this.forEach((value, name) => {
6779
- items.push([name, value]);
6780
- });
6781
- return items.values();
6782
- }
6783
- forEach(callback) {
6784
- for (const [name, entry] of this._entries.entries()) {
6785
- for (let i = 0; i < entry.length; i++) {
6786
- callback(entry[i], name, this);
6872
+ const iter = this[kEntries$1].entries();
6873
+ let i = 0;
6874
+ let key;
6875
+ let values;
6876
+ return {
6877
+ [Symbol.iterator]() {
6878
+ return this;
6879
+ },
6880
+ next() {
6881
+ if (values) {
6882
+ if (i >= values.length) {
6883
+ values = undefined;
6884
+ i = 0;
6885
+ }
6886
+ }
6887
+ if (!values) {
6888
+ const n = iter.next();
6889
+ if (n.done)
6890
+ return { done: true, value: undefined };
6891
+ key = n.value[0];
6892
+ values = n.value[1];
6893
+ }
6894
+ return {
6895
+ done: false,
6896
+ value: [key, values[i++]]
6897
+ };
6787
6898
  }
6899
+ };
6900
+ }
6901
+ forEach(callbackFn, thisArg) {
6902
+ const iterator = this.entries();
6903
+ let entry = iterator.next();
6904
+ while (!entry.done) {
6905
+ callbackFn.call(thisArg || this, entry.value[1], entry.value[0], this);
6906
+ entry = iterator.next();
6788
6907
  }
6789
6908
  }
6790
- get(name, index) {
6791
- const entry = this._entries.get(name);
6792
- const v = entry && entry[index || 0];
6793
- return v == null ? null : v;
6909
+ /**
6910
+ * Retrieves value of a given parameter at given index
6911
+ */
6912
+ get(name, index = 0) {
6913
+ const values = this[kEntries$1].get(name.toLowerCase());
6914
+ return values && values.length > index ? values[index] : null;
6794
6915
  }
6916
+ /**
6917
+ * Retrieves an array of values for a given parameter.
6918
+ */
6795
6919
  getAll(name) {
6796
- const entry = this._entries.get(name);
6797
- return entry ? entry.slice(0) : [];
6798
- }
6799
- has(name) {
6800
- return this._entries.has(name);
6920
+ const entry = this[kEntries$1].get(name);
6921
+ return entry ? entry.slice(0) : null;
6801
6922
  }
6923
+ /**
6924
+ * Retrieves the names of the parameters.
6925
+ */
6802
6926
  keys() {
6803
- return this._entries.keys();
6804
- }
6805
- set(name, value) {
6806
- this._delete(name);
6807
- this._add(name, value);
6808
- this.emit('change');
6809
- }
6810
- sort(compareFn) {
6811
- this._entries.sort(compareFn);
6812
- this.emit('change');
6927
+ return this[kEntries$1].keys();
6813
6928
  }
6929
+ /**
6930
+ * Retrieves the names of the parameters.
6931
+ */
6814
6932
  values() {
6815
6933
  const items = [];
6816
6934
  this.forEach((value) => items.push(value));
6817
6935
  return items.values();
6818
6936
  }
6937
+ /**
6938
+ * Checks for existence of a parameter.
6939
+ */
6940
+ has(name) {
6941
+ return this[kEntries$1].has(name);
6942
+ }
6943
+ /**
6944
+ * Sets or modifies a value for a given parameter.
6945
+ * If the header already exists, its value is replaced with the given value
6946
+ */
6947
+ set(name, value) {
6948
+ this._set(name, value);
6949
+ this.changed();
6950
+ return this;
6951
+ }
6952
+ sort(compareFn) {
6953
+ this[kEntries$1].sort(compareFn);
6954
+ this.changed();
6955
+ return this;
6956
+ }
6957
+ /**
6958
+ * Serializes the body to an encoded string, where key-value pairs (separated by `=`) are
6959
+ * separated by `&`s.
6960
+ */
6819
6961
  toString() {
6820
- let out = '';
6962
+ const out = [];
6821
6963
  this.forEach((v, k) => {
6822
- const qi = this._params.get(k);
6823
- const format = qi
6824
- ? (typeof qi.format === 'string' ? internalFormats[qi.format] : qi.format)
6825
- : undefined;
6826
- const stringify = (x) => encodeURIComponent(format ? format.stringify(x, k) : (x == null ? '' : '' + x));
6827
- const val = Array.isArray(v)
6828
- ? v.map(stringify).join(qi?.arrayDelimiter || ',')
6829
- : stringify(v);
6830
- if (val) {
6831
- if (out.length > 0)
6832
- out += '&';
6833
- out += k + '=' + val;
6834
- }
6964
+ out.push(this.encodeKey(k) +
6965
+ (v ? '=' + this.encodeValue(v, k) : ''));
6835
6966
  });
6836
- return out;
6967
+ return out.join('&');
6837
6968
  }
6838
- parse(input) {
6839
- this._entries.clear();
6840
- this._size = 0;
6841
- if (input && input.startsWith('?'))
6842
- input = input.substring(1);
6843
- if (!input)
6844
- return;
6845
- const tokenizer = tokenize(input, { delimiters: '&', quotes: true, brackets: true });
6846
- for (const token of tokenizer) {
6847
- if (!token)
6848
- continue;
6849
- const itemTokenizer = tokenize(token, {
6850
- delimiters: '=',
6851
- quotes: true,
6852
- brackets: true,
6853
- });
6854
- const k = decodeURIComponent(itemTokenizer.next() || '');
6855
- const v = itemTokenizer.join('=');
6856
- const qi = this._params.get(k);
6857
- if (qi?.array) {
6858
- const values = splitString(v, {
6859
- delimiters: qi?.arrayDelimiter || ',',
6969
+ define(name, options) {
6970
+ if (!name)
6971
+ throw new Error('Parameter name required');
6972
+ if (typeof options?.codec === 'string' && !internalCodecs[options.codec])
6973
+ throw new Error(`Unknown url parameter format name "${options.codec}"`);
6974
+ const codec = (typeof options?.codec === 'string'
6975
+ ? internalCodecs[options.codec]
6976
+ : options?.codec) || internalCodecs.string;
6977
+ const meta = {
6978
+ ...options,
6979
+ codec
6980
+ };
6981
+ this[kParamDefs].set(name, meta);
6982
+ return this;
6983
+ }
6984
+ encodeKey(key) {
6985
+ return (this[kOptions$1].encodeKey || defaultKeyEncoder)(key);
6986
+ }
6987
+ decodeKey(key) {
6988
+ return (this[kOptions$1].decodeKey || defaultKeyDecoder)(key);
6989
+ }
6990
+ encodeValue(value, key) {
6991
+ const prmDef = this[kParamDefs].get(key);
6992
+ if (prmDef) {
6993
+ const delimReplace = '%' + (prmDef.arrayDelimiter || ',').charCodeAt(0).toString(16).toUpperCase();
6994
+ const fn = (x) => encodeURIParam(prmDef.codec.encode(x)).replaceAll(',', delimReplace);
6995
+ return Array.isArray(value)
6996
+ ? value.map((v) => fn(v)).join(prmDef.arrayDelimiter || ',')
6997
+ : fn(value);
6998
+ }
6999
+ return (this[kOptions$1].encodeValue || defaultValueEncoder)(value);
7000
+ }
7001
+ decodeValue(value, key) {
7002
+ const prmDef = this[kParamDefs].get(key);
7003
+ const valueDecoder = (this[kOptions$1].decodeValue || defaultValueDecoder);
7004
+ let val = value;
7005
+ if (prmDef) {
7006
+ if (prmDef.array) {
7007
+ val = splitString(value, {
7008
+ delimiters: prmDef.arrayDelimiter || ',',
6860
7009
  brackets: true,
6861
- quotes: true
6862
- }).map((x) => decodeURIComponent(x));
6863
- this._add(k, values);
7010
+ quotes: true,
7011
+ keepQuotes: false
7012
+ }).map((x) => valueDecoder(x));
6864
7013
  }
6865
- else {
6866
- this._add(k, decodeURIComponent(v));
7014
+ else
7015
+ val = valueDecoder(val);
7016
+ const fn = (x) => prmDef.codec.decode(valueDecoder(x));
7017
+ val = Array.isArray(val) ? val.map(fn) : fn(val);
7018
+ if (prmDef.array === 'strict')
7019
+ val = Array.isArray(val) ? val : [val];
7020
+ else if (prmDef.array)
7021
+ val = Array.isArray(val) && val.length === 1 ? val[0] : val;
7022
+ if (Array.isArray(val)) {
7023
+ if (prmDef.minArrayItems && val.length < prmDef.minArrayItems)
7024
+ throw new Error(`"${key}" parameter requires at least ${prmDef.minArrayItems} values`);
7025
+ if (prmDef.maxArrayItems && val.length > prmDef.maxArrayItems)
7026
+ throw new Error(`"${key}" parameter accepts up to ${prmDef.maxArrayItems} values`);
6867
7027
  }
7028
+ return val;
6868
7029
  }
6869
- this.emit('change');
7030
+ return valueDecoder(value);
6870
7031
  }
6871
- toURLSearchParams() {
6872
- const out = new URLSearchParams();
6873
- this.forEach((v, k) => {
6874
- const qi = this._params.get(k);
6875
- const format = qi
6876
- ? (typeof qi.format === 'string' ? internalFormats[qi.format] : qi.format)
6877
- : undefined;
6878
- const stringify = (x) => format ? format.stringify(x, k) : (x == null ? '' : '' + x);
6879
- const val = Array.isArray(v)
6880
- ? v.map(stringify).join(qi?.arrayDelimiter || ',')
6881
- : stringify(v);
6882
- out.append(k, val);
6883
- });
6884
- return out;
7032
+ _append(name, value) {
7033
+ let values = this[kEntries$1].get(name);
7034
+ if (!values) {
7035
+ values = [];
7036
+ this[kEntries$1].set(name, values);
7037
+ }
7038
+ values.push(value ?? null);
7039
+ this[kSize$1] += 1;
6885
7040
  }
6886
- [Symbol.iterator]() {
6887
- return this.entries();
7041
+ _delete(name, value) {
7042
+ const oldValues = this[kEntries$1].get(name);
7043
+ if (!oldValues)
7044
+ return false;
7045
+ const oldSize = this[kSize$1];
7046
+ if (value) {
7047
+ const valueToDelete = Array.isArray(value) ? value : [value];
7048
+ const newValues = oldValues.filter(x => !valueToDelete.includes(x));
7049
+ this[kEntries$1].set(name, newValues);
7050
+ this[kSize$1] += -oldValues.length + newValues.length;
7051
+ }
7052
+ else {
7053
+ this[kEntries$1].delete(name);
7054
+ this[kSize$1] -= oldValues.length;
7055
+ }
7056
+ return oldSize !== this[kSize$1];
6888
7057
  }
6889
- get [Symbol.toStringTag]() {
6890
- return 'URLSearchParams';
7058
+ _set(name, value, index) {
7059
+ if (value == null) {
7060
+ this._delete(name);
7061
+ return;
7062
+ }
7063
+ const values = this[kEntries$1].get(name);
7064
+ if (!values) {
7065
+ this[kEntries$1].set(name, [value]);
7066
+ this[kSize$1] += 1;
7067
+ return;
7068
+ }
7069
+ if (index == null || index < 0) {
7070
+ this[kEntries$1].set(name, [value]);
7071
+ this[kSize$1] += -(values.length) + 1;
7072
+ return;
7073
+ }
7074
+ const oldLen = values.length;
7075
+ values[Math.min(index, values.length)] = value;
7076
+ this[kSize$1] += -oldLen + values.length;
6891
7077
  }
6892
- [nodeInspectCustom$1]() {
6893
- return this._entries;
7078
+ [(_a$2 = kEntries$1, _b$1 = kSize$1, _c = kParamDefs, Symbol.iterator)]() {
7079
+ return this.entries();
6894
7080
  }
6895
- _delete(name) {
6896
- const a = this._entries.get(name);
6897
- if (!a)
6898
- return false;
6899
- this._size -= a.length;
6900
- this._entries.delete(name);
6901
- return true;
7081
+ get [Symbol.toStringTag]() {
7082
+ return 'HttpParams';
6902
7083
  }
6903
- _add(name, value) {
6904
- const qi = this._params.get(name);
6905
- const format = qi ?
6906
- (typeof qi.format === 'string' ? internalFormats[qi.format] : qi.format) : undefined;
6907
- const fn = (x) => format ? format.parse(x, name) : x;
6908
- let v = Array.isArray(value) ? value.map(fn) : fn(value);
6909
- if (qi) {
6910
- if (qi.array === 'strict')
6911
- v = Array.isArray(v) ? v : [v];
6912
- else if (qi.array)
6913
- v = Array.isArray(v) && v.length === 1 ? v[0] : v;
6914
- if (Array.isArray(v)) {
6915
- if (qi.minArrayItems && v.length < qi.minArrayItems)
6916
- throw new Error(`"${name}" parameter requires at least ${qi.minArrayItems} values`);
6917
- if (qi.maxArrayItems && v.length > qi.maxArrayItems)
6918
- throw new Error(`"${name}" parameter accepts up to ${qi.maxArrayItems} values`);
7084
+ }
7085
+ HttpParams.kEntries = kEntries$1;
7086
+ HttpParams.kSize = kSize$1;
7087
+ HttpParams.kParamDefs = kParamDefs;
7088
+ HttpParams.kOptions = kOptions$1;
7089
+
7090
+ class OpraURLSearchParams extends HttpParams {
7091
+ constructor(init, options) {
7092
+ super(init, {
7093
+ ...options,
7094
+ params: {
7095
+ '$filter': { codec: 'filter' },
7096
+ '$limit': { codec: new IntegerCodec({ min: 0 }) },
7097
+ '$skip': { codec: new IntegerCodec({ min: 0 }) },
7098
+ '$pick': { codec: 'string', array: 'strict' },
7099
+ '$omit': { codec: 'string', array: 'strict' },
7100
+ '$include': { codec: 'string', array: 'strict' },
7101
+ '$sort': { codec: 'string', array: 'strict' },
7102
+ '$distinct': { codec: 'boolean' },
7103
+ '$count': { codec: 'boolean' },
7104
+ ...options?.params
6919
7105
  }
6920
- }
6921
- let entry = this._entries.get(name);
6922
- if (!entry) {
6923
- entry = [];
6924
- this._entries.set(name, entry);
6925
- }
6926
- entry.push(v);
6927
- this._size++;
6928
- return true;
7106
+ });
7107
+ }
7108
+ get [Symbol.toStringTag]() {
7109
+ return 'URLSearchParams';
6929
7110
  }
6930
7111
  }
6931
7112
 
6932
- const nodeInspectCustom = Symbol.for('nodejs.util.inspect.custom');
7113
+ var _a$1;
7114
+ const nodeInspectCustom$1 = Symbol.for('nodejs.util.inspect.custom');
6933
7115
  const urlRegEx = /^(?:((?:[A-Z][A-Z+-.]+:)+)\/\/([^/?]+))?(.*)?$/i;
6934
7116
  const schemeRegEx = /^([A-Z][A-Z+-.]+:?)+$/i;
6935
7117
  const hostRegEx = /^([^/:]+)(?::(\d+))?$/;
6936
7118
  const hostnameRegEx = /^([^/:]+)$/;
6937
- const CONTEXT_KEY = Symbol.for('opra.url.context');
6938
- const PATH_KEY = Symbol.for('opra.url.path');
6939
- const SEARCHPARAMS_KEY = Symbol.for('opra.url.searchparams');
7119
+ const kContext = Symbol('kContext');
7120
+ const kPath = Symbol('kPath');
7121
+ const kSearchParams = Symbol('kSearchParams');
6940
7122
  class OpraURL {
6941
- constructor(input, pathPrefix) {
6942
- Object.defineProperty(this, CONTEXT_KEY, {
6943
- writable: true,
6944
- configurable: true,
6945
- enumerable: false,
6946
- value: {}
6947
- });
6948
- Object.defineProperty(this, PATH_KEY, {
6949
- writable: true,
6950
- configurable: true,
6951
- enumerable: false,
6952
- value: new OpraURLPath()
7123
+ constructor(input, arg1) {
7124
+ this[_a$1] = {
7125
+ protocol: '',
7126
+ username: '',
7127
+ pathname: '',
7128
+ prefix: '',
7129
+ hostname: '',
7130
+ port: '',
7131
+ hash: '',
7132
+ password: '',
7133
+ search: '',
7134
+ address: '',
7135
+ needUpdate: true
7136
+ };
7137
+ this[kPath] = new OpraURLPath('', {
7138
+ onChange: () => this._changed()
6953
7139
  });
6954
- Object.defineProperty(this, SEARCHPARAMS_KEY, {
6955
- writable: true,
6956
- configurable: true,
6957
- enumerable: false,
6958
- value: new OpraURLSearchParams()
7140
+ this[kSearchParams] = new OpraURLSearchParams('', {
7141
+ onChange: () => this._changed()
6959
7142
  });
6960
- this.searchParams.on('change', () => this._invalidate());
6961
- this.path.on('change', () => this._invalidate());
6962
- if (pathPrefix)
6963
- this.setPrefix(pathPrefix);
7143
+ const base = typeof arg1 === 'object' ? arg1.base : arg1;
7144
+ if (typeof arg1 === 'object') {
7145
+ const defineParams = arg1?.params;
7146
+ if (defineParams)
7147
+ Object.keys(defineParams).forEach(key => this.searchParams.define(key, defineParams[key]));
7148
+ }
6964
7149
  if (input)
6965
- this.parse(input);
7150
+ this.parse(typeof input === 'object' ? input.toString() : input);
7151
+ if (base) {
7152
+ const baseUrl = base instanceof OpraURL ? base : new OpraURL(base);
7153
+ this[kContext].protocol = baseUrl.protocol;
7154
+ this[kContext].hostname = baseUrl.hostname;
7155
+ this[kContext].port = baseUrl.port;
7156
+ this[kContext].prefix = baseUrl.pathname;
7157
+ }
6966
7158
  }
6967
7159
  get address() {
6968
7160
  this._update();
6969
- let out = '';
6970
- if (this.hostname) {
6971
- out += this.protocol + '//' +
6972
- (this.username || this.password
6973
- ? ((this.username ? encodeURIComponent(this.username) : '') +
6974
- (this.password ? ':' + encodeURIComponent(this.password) : '') + '@')
6975
- : '') + this.host;
6976
- }
6977
- return out + this.pathPrefix + this.pathname;
7161
+ return this[kContext].address;
6978
7162
  }
6979
- get href() {
6980
- return this.address + this.search + this.hash;
7163
+ get host() {
7164
+ return this.hostname ? (this.hostname + (this.port ? ':' + this.port : '')) : '';
6981
7165
  }
6982
- get protocol() {
6983
- return this[CONTEXT_KEY].protocol || 'http:';
7166
+ set host(v) {
7167
+ if (v) {
7168
+ const m = hostRegEx.exec(v);
7169
+ if (!m)
7170
+ throw Object.assign(new TypeError('Invalid host'), {
7171
+ host: v,
7172
+ code: 'ERR_INVALID_URL'
7173
+ });
7174
+ this[kContext].hostname = m[1];
7175
+ this[kContext].port = m[2] || '';
7176
+ }
7177
+ else {
7178
+ this[kContext].hostname = '';
7179
+ this[kContext].port = '';
7180
+ }
7181
+ this._changed();
6984
7182
  }
6985
- set protocol(v) {
6986
- if (!schemeRegEx.test(v))
6987
- throw Object.assign(new TypeError('Invalid protocol'), {
6988
- protocol: v,
6989
- code: 'ERR_INVALID_URL'
6990
- });
6991
- this[CONTEXT_KEY].protocol = v + (v.endsWith(':') ? '' : ':');
7183
+ get hostname() {
7184
+ return this[kContext].hostname || '';
6992
7185
  }
6993
- get username() {
6994
- return this[CONTEXT_KEY].username || '';
7186
+ set hostname(v) {
7187
+ if (v) {
7188
+ if (!hostnameRegEx.test(v))
7189
+ throw Object.assign(new TypeError('Invalid hostname'), {
7190
+ hostname: v,
7191
+ code: 'ERR_INVALID_URL'
7192
+ });
7193
+ this[kContext].hostname = v;
7194
+ }
7195
+ else
7196
+ this[kContext].hostname = '';
7197
+ this._changed();
6995
7198
  }
6996
- set username(v) {
6997
- this[CONTEXT_KEY].username = v;
7199
+ get href() {
7200
+ return this.address + this.search + this.hash;
6998
7201
  }
6999
7202
  get password() {
7000
- return this[CONTEXT_KEY].password || '';
7203
+ return this[kContext].password;
7001
7204
  }
7002
7205
  set password(v) {
7003
- this[CONTEXT_KEY].password = v;
7206
+ this[kContext].password = v || '';
7207
+ this._changed();
7004
7208
  }
7005
- get host() {
7006
- return this.hostname ? (this.hostname + (this.port ? ':' + this.port : '')) : '';
7209
+ get port() {
7210
+ return this[kContext].port;
7007
7211
  }
7008
- set host(v) {
7009
- const m = hostRegEx.exec(v);
7010
- if (!m)
7011
- throw Object.assign(new TypeError('Invalid host'), {
7012
- host: v,
7013
- code: 'ERR_INVALID_URL'
7014
- });
7015
- this[CONTEXT_KEY].hostname = m[1];
7016
- this[CONTEXT_KEY].port = m[2] ? parseInt(m[2], 10) : null;
7212
+ set port(value) {
7213
+ if (value) {
7214
+ // noinspection SuspiciousTypeOfGuard
7215
+ const v = parseInt(value, 10);
7216
+ if (isNaN(v) || v < 1 || v > 35535 || v % 1 > 0)
7217
+ throw Object.assign(new TypeError('Invalid port'), {
7218
+ hostname: v,
7219
+ code: 'ERR_INVALID_URL'
7220
+ });
7221
+ this[kContext].port = value;
7222
+ }
7223
+ else
7224
+ this[kContext].port = '';
7225
+ this._changed();
7017
7226
  }
7018
- get hostname() {
7019
- return this[CONTEXT_KEY].hostname || '';
7227
+ get prefix() {
7228
+ return this[kContext].prefix;
7020
7229
  }
7021
- set hostname(v) {
7022
- if (!hostnameRegEx.test(v))
7023
- throw Object.assign(new TypeError('Invalid hostname'), {
7024
- hostname: v,
7025
- code: 'ERR_INVALID_URL'
7026
- });
7027
- this[CONTEXT_KEY].hostname = v;
7230
+ set prefix(value) {
7231
+ if (value) {
7232
+ const url = new OpraURL(value);
7233
+ this[kContext].prefix = url.pathname;
7234
+ }
7235
+ else
7236
+ this[kContext].prefix = '';
7237
+ this._changed();
7028
7238
  }
7029
- get port() {
7030
- const v = this[CONTEXT_KEY].port;
7031
- return v == null ? null : v;
7239
+ get protocol() {
7240
+ return this[kContext].protocol || 'http:';
7032
7241
  }
7033
- set port(v) {
7034
- if (v == null) {
7035
- this[CONTEXT_KEY].port = null;
7036
- return;
7242
+ set protocol(v) {
7243
+ if (v) {
7244
+ if (!schemeRegEx.test(v))
7245
+ throw Object.assign(new TypeError('Invalid protocol'), {
7246
+ protocol: v,
7247
+ code: 'ERR_INVALID_URL'
7248
+ });
7249
+ this[kContext].protocol = v + (v.endsWith(':') ? '' : ':');
7037
7250
  }
7038
- // noinspection SuspiciousTypeOfGuard
7039
- if (typeof v !== 'number' || isNaN(v) || v < 1 || v > 35535 || v % 1 > 0)
7040
- throw Object.assign(new TypeError('Invalid port'), {
7041
- hostname: v,
7042
- code: 'ERR_INVALID_URL'
7043
- });
7044
- this[CONTEXT_KEY].port = v;
7251
+ else
7252
+ this[kContext].protocol = '';
7253
+ this._changed();
7045
7254
  }
7046
- get origin() {
7047
- return this.hostname ? (this.protocol + '//' + this.hostname) : '';
7255
+ get username() {
7256
+ return this[kContext].username;
7048
7257
  }
7049
- get pathPrefix() {
7050
- return this[CONTEXT_KEY].pathPrefix || '';
7258
+ set username(v) {
7259
+ this[kContext].username = v || '';
7260
+ this._changed();
7051
7261
  }
7052
- set pathPrefix(v) {
7053
- if (!v) {
7054
- this[CONTEXT_KEY].pathPrefix = '';
7055
- return;
7056
- }
7057
- v = normalizePath(tokenize(v, { delimiters: '#?', quotes: true, brackets: true }).next() || '', true);
7058
- if (v.includes('://'))
7059
- this[CONTEXT_KEY].pathPrefix = v;
7060
- else
7061
- this[CONTEXT_KEY].pathPrefix = v ? '/' + v : '';
7262
+ get origin() {
7263
+ return this.hostname ? (this.protocol + '//' + this.hostname) : '';
7062
7264
  }
7063
7265
  get path() {
7064
- return this[PATH_KEY];
7266
+ return this[kPath];
7065
7267
  }
7066
7268
  get pathname() {
7067
7269
  this._update();
7068
- return this[CONTEXT_KEY].pathname || '';
7270
+ return this[kContext].pathname || '';
7069
7271
  }
7070
7272
  set pathname(v) {
7071
7273
  this._setPathname(v, false);
7072
7274
  }
7073
7275
  get searchParams() {
7074
- return this[SEARCHPARAMS_KEY];
7276
+ return this[kSearchParams];
7075
7277
  }
7076
7278
  get hash() {
7077
- return this[CONTEXT_KEY].hash || '';
7279
+ return this[kContext].hash || '';
7078
7280
  }
7079
7281
  set hash(v) {
7080
- this[CONTEXT_KEY].hash = v ? (v.startsWith('#') ? v : '#' + v) : '';
7282
+ this[kContext].hash = v ? (v.startsWith('#') ? v : '#' + v) : '';
7283
+ this._changed();
7081
7284
  }
7082
7285
  get search() {
7083
7286
  this._update();
7084
- return this[CONTEXT_KEY].search || '';
7287
+ return this[kContext].search || '';
7085
7288
  }
7086
7289
  set search(v) {
7087
- this.searchParams.parse(v);
7290
+ this.searchParams.clear();
7291
+ this.searchParams.appendAll(v);
7292
+ }
7293
+ parse(input) {
7294
+ const m = urlRegEx.exec(input);
7295
+ if (!m)
7296
+ throw Object.assign(new TypeError('Invalid URL'), {
7297
+ input,
7298
+ code: 'ERR_INVALID_URL'
7299
+ });
7300
+ this.protocol = m[1];
7301
+ const isAbsolute = !!m[2];
7302
+ if (isAbsolute) {
7303
+ let tokens = splitString(m[2], { delimiters: '@' });
7304
+ if (tokens.length > 1) {
7305
+ this.host = tokens[1];
7306
+ tokens = splitString(tokens[0], { delimiters: ':' });
7307
+ this.username = tokens[0] ? decodeURIComponent(tokens[0]) : '';
7308
+ this.password = tokens[1] ? decodeURIComponent(tokens[1]) : '';
7309
+ }
7310
+ else
7311
+ this.host = tokens[0];
7312
+ }
7313
+ else {
7314
+ this.host = '';
7315
+ this.username = '';
7316
+ this.password = '';
7317
+ }
7318
+ input = m[3] || '';
7319
+ let tokenizer = tokenize(input, { delimiters: '#', quotes: true, brackets: true });
7320
+ input = tokenizer.next() || '';
7321
+ this.hash = tokenizer.join('#');
7322
+ tokenizer = tokenize(input, { delimiters: '?', quotes: true, brackets: true });
7323
+ this._setPathname(tokenizer.next() || '', isAbsolute);
7324
+ this.searchParams.clear();
7325
+ this.searchParams.appendAll(tokenizer.join('&'));
7326
+ this._changed();
7088
7327
  }
7089
- addPath(name, key) {
7090
- this.path.add(name, key);
7328
+ join(...source) {
7329
+ this.path.join(...source);
7091
7330
  return this;
7092
7331
  }
7093
- addSearchParam(name, value) {
7332
+ addParam(name, value) {
7094
7333
  this.searchParams.append(name, value);
7095
7334
  return this;
7096
7335
  }
7336
+ setParam(name, value) {
7337
+ this.searchParams.set(name, value);
7338
+ return this;
7339
+ }
7097
7340
  setHost(v) {
7098
7341
  this.host = v;
7099
7342
  return this;
@@ -7107,11 +7350,11 @@ class OpraURL {
7107
7350
  return this;
7108
7351
  }
7109
7352
  setPort(v) {
7110
- this.port = v;
7353
+ this.port = v ? String(v) : '';
7111
7354
  return this;
7112
7355
  }
7113
7356
  setPrefix(v) {
7114
- this.pathPrefix = v;
7357
+ this.prefix = v;
7115
7358
  return this;
7116
7359
  }
7117
7360
  setPathname(v) {
@@ -7126,46 +7369,11 @@ class OpraURL {
7126
7369
  this.search = v;
7127
7370
  return this;
7128
7371
  }
7129
- setSearchParam(name, value) {
7130
- this.searchParams.set(name, value);
7131
- return this;
7132
- }
7133
- parse(input) {
7134
- const m = urlRegEx.exec(input);
7135
- if (!m)
7136
- throw Object.assign(new TypeError('Invalid URL'), {
7137
- input,
7138
- code: 'ERR_INVALID_URL'
7139
- });
7140
- if (m[1])
7141
- this.protocol = m[1];
7142
- if (m[2]) {
7143
- let tokens = splitString(m[2], { delimiters: '@' });
7144
- if (tokens.length > 1) {
7145
- this.host = tokens[1];
7146
- tokens = splitString(tokens[0], { delimiters: ':' });
7147
- this.username = tokens[0] ? decodeURIComponent(tokens[0]) : '';
7148
- this.password = tokens[1] ? decodeURIComponent(tokens[1]) : '';
7149
- }
7150
- else
7151
- this.host = tokens[0];
7152
- }
7153
- input = m[3] || '';
7154
- let tokenizer = tokenize(input, { delimiters: '#', quotes: true, brackets: true });
7155
- input = tokenizer.next() || '';
7156
- this.hash = tokenizer.join('#');
7157
- tokenizer = tokenize(input, { delimiters: '?', quotes: true, brackets: true });
7158
- this._setPathname(tokenizer.next() || '', true);
7159
- // this.path.join()
7160
- this.searchParams.clear();
7161
- this.searchParams.parse(tokenizer.join('&'));
7162
- return this;
7163
- }
7164
7372
  toString() {
7165
7373
  return this.href;
7166
7374
  }
7167
7375
  /* istanbul ignore next */
7168
- [nodeInspectCustom]() {
7376
+ [(_a$1 = kContext, nodeInspectCustom$1)]() {
7169
7377
  this._update();
7170
7378
  return {
7171
7379
  protocol: this.protocol,
@@ -7174,7 +7382,7 @@ class OpraURL {
7174
7382
  host: this.host,
7175
7383
  hostname: this.hostname,
7176
7384
  origin: this.origin,
7177
- pathPrefix: this.pathPrefix,
7385
+ pathPrefix: this.prefix,
7178
7386
  path: this.path,
7179
7387
  pathname: this.pathname,
7180
7388
  search: this.search,
@@ -7182,27 +7390,34 @@ class OpraURL {
7182
7390
  hash: this.hash,
7183
7391
  };
7184
7392
  }
7185
- _invalidate() {
7186
- this[CONTEXT_KEY].needUpdate = true;
7187
- }
7188
7393
  _update() {
7189
- if (!this[CONTEXT_KEY].needUpdate)
7394
+ if (!this[kContext].needUpdate)
7190
7395
  return;
7191
- this[CONTEXT_KEY].needUpdate = false;
7396
+ const ctx = this[kContext];
7397
+ ctx.needUpdate = false;
7192
7398
  let s = this.path.toString();
7193
- this[CONTEXT_KEY].pathname = s ? '/' + s : '';
7399
+ ctx.pathname = s ? '/' + s : '';
7194
7400
  s = this.searchParams.toString();
7195
- this[CONTEXT_KEY].search = s ? '?' + s : '';
7401
+ ctx.search = s ? '?' + s : '';
7402
+ let address = '';
7403
+ if (ctx.hostname) {
7404
+ address += (ctx.protocol || 'http:') + '//' +
7405
+ (ctx.username || ctx.password
7406
+ ? ((ctx.username ? encodeURIComponent(ctx.username) : '') +
7407
+ (ctx.password ? ':' + encodeURIComponent(ctx.password) : '') + '@')
7408
+ : '') + this.host;
7409
+ }
7410
+ ctx.address = address + ctx.prefix + ctx.pathname;
7196
7411
  }
7197
- _setPathname(v, inclSvcRoot) {
7412
+ _setPathname(v, trimPrefix) {
7198
7413
  this.path.clear();
7199
7414
  if (!v)
7200
7415
  return;
7201
7416
  const pathTokenizer = tokenize(normalizePath(v, true), {
7202
7417
  delimiters: '/', quotes: true, brackets: true,
7203
7418
  });
7204
- if (inclSvcRoot && this.pathPrefix) {
7205
- const prefixTokenizer = tokenize(normalizePath(this.pathPrefix, true), {
7419
+ if (trimPrefix && this.prefix) {
7420
+ const prefixTokenizer = tokenize(normalizePath(this.prefix, true), {
7206
7421
  delimiters: '/', quotes: true, brackets: true,
7207
7422
  });
7208
7423
  for (const a of prefixTokenizer) {
@@ -7213,12 +7428,428 @@ class OpraURL {
7213
7428
  }
7214
7429
  for (const x of pathTokenizer) {
7215
7430
  const p = decodePathComponent(x);
7216
- this.path.add(p);
7431
+ this.path.join(p);
7217
7432
  }
7433
+ this._changed();
7434
+ }
7435
+ _changed() {
7436
+ this[kContext].needUpdate = true;
7218
7437
  }
7219
7438
  }
7439
+ OpraURL.kContext = kContext;
7440
+ OpraURL.kPath = kPath;
7441
+ OpraURL.kSearchParams = kSearchParams;
7220
7442
 
7221
- Buffer.from('\r\n');
7443
+ const crlfBuffer = Buffer.from('\r\n');
7444
+ const kHeaders = Symbol('kHeaders');
7445
+ const kHeadersCount = Symbol('kHeadersCount');
7446
+ const kTrailers = Symbol('kTrailers');
7447
+ const kTrailersCount = Symbol('kTrailersCount');
7448
+ // todo: Check is this class should be in common library
7449
+ class HttpRequestNode extends Readable {
7450
+ constructor() {
7451
+ super(...arguments);
7452
+ this.aborted = false;
7453
+ }
7454
+ get headers() {
7455
+ if (!this[kHeaders])
7456
+ this[kHeaders] = arrayToHeaders(this.rawHeaders);
7457
+ return this[kHeaders];
7458
+ }
7459
+ get headersCount() {
7460
+ return this[kHeadersCount];
7461
+ }
7462
+ get trailers() {
7463
+ if (!this[kTrailers])
7464
+ this[kTrailers] = arrayToHeaders(this.rawTrailers);
7465
+ return this[kTrailers];
7466
+ }
7467
+ get trailersCount() {
7468
+ return this[kTrailersCount];
7469
+ }
7470
+ _read() {
7471
+ if (this.data) {
7472
+ this.push(this.data);
7473
+ }
7474
+ this.push(null);
7475
+ }
7476
+ static parse(input) {
7477
+ const parser = new HTTPParser(HTTPParser.REQUEST);
7478
+ const out = new HttpRequestNode();
7479
+ const bodyChunks = [];
7480
+ parser[HTTPParser.kOnHeadersComplete] = function (req) {
7481
+ out.shouldKeepAlive = req.shouldKeepAlive;
7482
+ out.upgrade = req.upgrade;
7483
+ out.method = HTTPParser.methods[req.method];
7484
+ out.url = req.url;
7485
+ out.originalUrl = req.url;
7486
+ out.httpVersionMajor = req.versionMajor;
7487
+ out.httpVersionMinor = req.versionMinor;
7488
+ out.httpVersion = req.versionMajor + '.' + req.versionMinor;
7489
+ out.rawHeaders = req.headers;
7490
+ out[kHeadersCount] = Math.ceil(req.headers.length / 2);
7491
+ out[kTrailersCount] = 0;
7492
+ };
7493
+ parser[HTTPParser.kOnBody] = function (chunk, offset, length) {
7494
+ bodyChunks.push(chunk.subarray(offset, offset + length));
7495
+ };
7496
+ // This is actually the event for trailers, go figure.
7497
+ parser[HTTPParser.kOnHeaders] = function (t) {
7498
+ out.rawTrailers = t;
7499
+ out[kTrailersCount] = Math.ceil(t.length / 2);
7500
+ };
7501
+ parser[HTTPParser.kOnMessageComplete] = function () {
7502
+ out.complete = true;
7503
+ };
7504
+ // Since we are sending the entire Buffer at once here all callbacks above happen synchronously.
7505
+ // The parser does not do _anything_ asynchronous.
7506
+ // However, you can of course call execute() multiple times with multiple chunks, e.g. from a stream.
7507
+ // But then you have to refactor the entire logic to be async (e.g. resolve a Promise in kOnMessageComplete and add timeout logic).
7508
+ parser.execute(input);
7509
+ if (!out.complete)
7510
+ parser.execute(crlfBuffer);
7511
+ parser.finish();
7512
+ if (!out.complete) {
7513
+ throw new Error('Could not parse request');
7514
+ }
7515
+ out.rawTrailers = out.rawTrailers || [];
7516
+ if (bodyChunks.length)
7517
+ out.data = Buffer.concat(bodyChunks);
7518
+ out.resume();
7519
+ return out;
7520
+ }
7521
+ }
7522
+ function arrayToHeaders(arr) {
7523
+ const headers = {};
7524
+ for (let i = 0; i < arr.length; i++) {
7525
+ const k = arr[i].toLowerCase();
7526
+ const v = arr[++i];
7527
+ const trgV = headers[k];
7528
+ // Array header -- only Set-Cookie at the moment
7529
+ if (trgV && k === 'set-cookie') {
7530
+ const a = Array.isArray(trgV) ? trgV : [trgV];
7531
+ a.push(v);
7532
+ headers[k] = a;
7533
+ }
7534
+ else if (typeof trgV === 'string') {
7535
+ headers[k] += (k === 'cookie' ? '; ' : ', ') + v;
7536
+ }
7537
+ else
7538
+ headers[k] = v;
7539
+ }
7540
+ return headers;
7541
+ }
7542
+
7543
+ var _a, _b;
7544
+ const knownKeys = Object.keys(HttpHeaderCodes);
7545
+ const knownKeysLower = knownKeys.map(x => x.toLowerCase());
7546
+ const nodeInspectCustom = Symbol.for('nodejs.util.inspect.custom');
7547
+ const kEntries = Symbol('kEntries');
7548
+ const kSize = Symbol('kSize');
7549
+ const kOptions = Symbol('kOptions');
7550
+ class HttpHeaders {
7551
+ constructor(init, options) {
7552
+ this[_a] = new ResponsiveMap();
7553
+ this[_b] = 0;
7554
+ this[kOptions] = { ...options, onChange: undefined };
7555
+ if (init)
7556
+ this.appendAll(init);
7557
+ this[kOptions].onChange = options?.onChange;
7558
+ }
7559
+ get size() {
7560
+ return this[kSize];
7561
+ }
7562
+ /**
7563
+ * Appends a new value to the existing set of values for a header
7564
+ * and returns this instance
7565
+ */
7566
+ append(name, value) {
7567
+ this._append(name, value);
7568
+ this.changed();
7569
+ return this;
7570
+ }
7571
+ /**
7572
+ * Appends multiple values to the existing set of values for a header
7573
+ * and returns this instance
7574
+ */
7575
+ appendAll(headers) {
7576
+ if (typeof headers === 'string') {
7577
+ headers.split('\n').forEach(line => {
7578
+ const index = line.indexOf(':');
7579
+ if (index > 0) {
7580
+ const name = line.slice(0, index);
7581
+ const value = line.slice(index + 1).trim();
7582
+ this._append(name, value);
7583
+ }
7584
+ });
7585
+ }
7586
+ else if (headers.forEach && typeof headers.forEach === 'function')
7587
+ headers.forEach((value, name) => this._append(name, value));
7588
+ else
7589
+ Object.keys(headers).forEach(name => this._append(name, headers[name]));
7590
+ this.changed();
7591
+ return this;
7592
+ }
7593
+ changed() {
7594
+ if (this[kOptions].onChange)
7595
+ this[kOptions].onChange();
7596
+ }
7597
+ clear() {
7598
+ if (this[kEntries].size) {
7599
+ this[kEntries].clear();
7600
+ this[kSize] = 0;
7601
+ this.changed();
7602
+ }
7603
+ }
7604
+ /**
7605
+ * Deletes values for a given header
7606
+ */
7607
+ delete(name, value) {
7608
+ if (this._delete(name, value))
7609
+ this.changed();
7610
+ return this;
7611
+ }
7612
+ /**
7613
+ * Returns an iterable of key, value pairs for every entry in the map.
7614
+ */
7615
+ entries() {
7616
+ const iter = this[kEntries].entries();
7617
+ let i = 0;
7618
+ let key;
7619
+ let values;
7620
+ return {
7621
+ [Symbol.iterator]() {
7622
+ return this;
7623
+ },
7624
+ next() {
7625
+ if (values) {
7626
+ if (i >= values.length) {
7627
+ values = undefined;
7628
+ i = 0;
7629
+ }
7630
+ }
7631
+ if (!values) {
7632
+ const n = iter.next();
7633
+ if (n.done)
7634
+ return { done: true, value: undefined };
7635
+ key = n.value[0];
7636
+ values = n.value[1];
7637
+ }
7638
+ return {
7639
+ done: false,
7640
+ value: [key, values[i++]]
7641
+ };
7642
+ }
7643
+ };
7644
+ }
7645
+ forEach(callbackFn, thisArg) {
7646
+ const iterator = this.entries();
7647
+ let entry = iterator.next();
7648
+ while (!entry.done) {
7649
+ callbackFn.call(thisArg || this, entry.value[1], entry.value[0], this);
7650
+ entry = iterator.next();
7651
+ }
7652
+ }
7653
+ /**
7654
+ * Retrieves value of a given header at given index
7655
+ */
7656
+ get(name, index = 0) {
7657
+ const values = this[kEntries].get(name.toLowerCase());
7658
+ return values && values.length > index ? values[index] : null;
7659
+ }
7660
+ /**
7661
+ * Retrieves an array of values for a given header.
7662
+ */
7663
+ getAll(name) {
7664
+ const entry = this[kEntries].get(name);
7665
+ return entry ? entry.slice(0) : null;
7666
+ }
7667
+ /**
7668
+ * Retrieves the names of the headers.
7669
+ */
7670
+ keys() {
7671
+ return this[kEntries].keys();
7672
+ }
7673
+ /**
7674
+ * Checks for existence of a given header.
7675
+ */
7676
+ has(name) {
7677
+ return this[kEntries].has(name);
7678
+ }
7679
+ /**
7680
+ * Sets or modifies a value for a given header.
7681
+ * If the header already exists, its value is replaced with the given value
7682
+ */
7683
+ set(name, value) {
7684
+ this._set(name, String(value));
7685
+ this.changed();
7686
+ return this;
7687
+ }
7688
+ sort(compareFn) {
7689
+ this[kEntries].sort(compareFn);
7690
+ this.changed();
7691
+ return this;
7692
+ }
7693
+ _append(name, value) {
7694
+ const i = knownKeysLower.indexOf(name);
7695
+ const normalizedName = knownKeys[i] || name;
7696
+ let values = this[kEntries].get(normalizedName);
7697
+ if (!values) {
7698
+ values = [];
7699
+ this[kEntries].set(normalizedName, values);
7700
+ }
7701
+ const oldSize = values.length;
7702
+ if (Array.isArray(value))
7703
+ values.push(...value.map(x => String(x)));
7704
+ else
7705
+ values.push(String(value));
7706
+ this[kSize] = -oldSize + values.length;
7707
+ }
7708
+ _delete(name, value) {
7709
+ const oldValues = this[kEntries].get(name);
7710
+ if (!oldValues)
7711
+ return false;
7712
+ const oldSize = this[kSize];
7713
+ if (value) {
7714
+ const valueToDelete = Array.isArray(value) ? value.map(x => String(x)) : [String(value)];
7715
+ const newValues = oldValues.filter(x => !valueToDelete.includes(x));
7716
+ this[kEntries].set(name, newValues);
7717
+ this[kSize] += -oldValues.length + newValues.length;
7718
+ }
7719
+ else {
7720
+ this[kEntries].delete(name);
7721
+ this[kSize] -= oldValues.length;
7722
+ }
7723
+ return oldSize !== this[kSize];
7724
+ }
7725
+ _set(name, value) {
7726
+ if (value == null) {
7727
+ this._delete(name);
7728
+ return;
7729
+ }
7730
+ const oldValues = this[kEntries].get(name);
7731
+ const i = knownKeysLower.indexOf(name);
7732
+ const normalizedName = knownKeys[i] || name;
7733
+ const newValues = Array.isArray(value) ? value : [value];
7734
+ this[kEntries].set(normalizedName, newValues);
7735
+ this[kSize] += -(oldValues?.length || 0) + newValues.length;
7736
+ }
7737
+ [(_a = kEntries, _b = kSize, nodeInspectCustom)]() {
7738
+ return this[kEntries];
7739
+ }
7740
+ [Symbol.iterator]() {
7741
+ return this.entries();
7742
+ }
7743
+ get [Symbol.toStringTag]() {
7744
+ return 'HttpHeaders';
7745
+ }
7746
+ }
7747
+ HttpHeaders.kEntries = kEntries;
7748
+ HttpHeaders.kSize = kSize;
7749
+ HttpHeaders.kOptions = kOptions;
7750
+
7751
+ /// <reference lib="dom" />
7752
+ const directCopyProperties = ['cache', 'credentials', 'destination', 'headers', 'integrity',
7753
+ 'keepalive', 'mode', 'redirect', 'referrer', 'referrerPolicy'];
7754
+ class HttpRequest {
7755
+ constructor(init) {
7756
+ this.cache = init?.cache || 'default';
7757
+ this.credentials = init?.credentials || 'same-origin';
7758
+ this.destination = init?.destination || '';
7759
+ this.headers = new HttpHeaders(init?.headers);
7760
+ this.integrity = init?.integrity || '';
7761
+ this.keepalive = init?.keepalive ?? false;
7762
+ this.method = (init?.method || 'GET').toUpperCase();
7763
+ this.mode = init?.mode || 'cors';
7764
+ this.redirect = init?.redirect || 'follow';
7765
+ this.mode = init?.mode || 'cors';
7766
+ this.referrer = init?.referrer || '';
7767
+ this.referrerPolicy = init?.referrerPolicy || '';
7768
+ this.signal = init?.signal || new AbortController().signal;
7769
+ this.body = init?.body;
7770
+ this.urlInstance = new OpraURL(init?.url);
7771
+ if (init?.params)
7772
+ this.params.appendAll(init.params);
7773
+ }
7774
+ /** Returns the URL of request as a string. */
7775
+ get url() {
7776
+ return this.urlInstance.href;
7777
+ }
7778
+ set url(value) {
7779
+ this.urlInstance.parse(value);
7780
+ }
7781
+ /** Returns the searchParams of the URL as OpraURLSearchParams */
7782
+ get params() {
7783
+ return this.urlInstance.searchParams;
7784
+ }
7785
+ /** Returns the path part of URL as OpraURLPath */
7786
+ get path() {
7787
+ return this.urlInstance.path;
7788
+ }
7789
+ clone(...update) {
7790
+ const out = new HttpRequest();
7791
+ out.merge(this);
7792
+ for (const upd of update) {
7793
+ out.merge(upd);
7794
+ }
7795
+ return out;
7796
+ }
7797
+ merge(update) {
7798
+ directCopyProperties.forEach(k => {
7799
+ if (update[k] != null)
7800
+ this[k] = update[k];
7801
+ });
7802
+ if (update.headers) {
7803
+ const h = update.headers instanceof HttpHeaders
7804
+ ? update.headers
7805
+ : new HttpHeaders(update.headers);
7806
+ h.forEach((v, k) => {
7807
+ if (k.toLowerCase() === 'set-cookie') {
7808
+ this.headers.append(k, v);
7809
+ }
7810
+ else
7811
+ this.headers.set(k, v);
7812
+ });
7813
+ }
7814
+ }
7815
+ inset(src) {
7816
+ directCopyProperties.forEach(k => {
7817
+ if (this[k] == null && src[k] != null)
7818
+ this[k] = src[k];
7819
+ });
7820
+ if (src.headers) {
7821
+ const h = src.headers instanceof HttpHeaders
7822
+ ? src.headers
7823
+ : new HttpHeaders(src.headers);
7824
+ h.forEach((v, k) => {
7825
+ if (k.toLowerCase() === 'set-cookie') {
7826
+ this.headers.append(k, v);
7827
+ }
7828
+ else if (!this.headers.has(k))
7829
+ this.headers.set(k, v);
7830
+ });
7831
+ }
7832
+ }
7833
+ }
7834
+
7835
+ class HttpResponse {
7836
+ constructor(init) {
7837
+ /**
7838
+ * Returns true if response has body to be received
7839
+ */
7840
+ this.hasBody = false;
7841
+ this.headers = new HttpHeaders(init?.headers);
7842
+ this.status = init?.status || 200;
7843
+ this.statusText = init?.statusText || 'OK';
7844
+ this.url = init?.url || null;
7845
+ this.ok = this.status >= 200 && this.status < 300;
7846
+ this.body = init?.body;
7847
+ this.hasBody = init?.body != null || !!init?.hasBody;
7848
+ }
7849
+ clone(update) {
7850
+ return new HttpResponse({ ...this, ...update });
7851
+ }
7852
+ }
7222
7853
 
7223
7854
  class ClientError extends Error {
7224
7855
  constructor(init, cause) {
@@ -7238,259 +7869,146 @@ const JSON_CONTENT_TYPE_PATTERN = /^application\/([\w-]+\+)?\bjson\b/i;
7238
7869
  const TEXT_CONTENT_TYPE_PATTERN = /^text\/.*$/i;
7239
7870
  const FORMDATA_CONTENT_TYPE_PATTERN = /^multipart\/\bform-data\b/i;
7240
7871
 
7241
- class HttpRequest extends Observable {
7242
- constructor(_handler, options = {}) {
7872
+ const kHandler = Symbol('kHandler');
7873
+ const kRequest = Symbol('kRequest');
7874
+ class HttpRequestHost extends Observable {
7875
+ constructor(handler, options) {
7243
7876
  super((subscriber) => {
7244
- if (options.observe === 'response') {
7245
- this.fetch().then(v => {
7246
- subscriber.next(v);
7247
- subscriber.complete();
7248
- }).catch(e => subscriber.error(e));
7249
- return;
7250
- }
7251
- this.resolve().then(v => {
7252
- subscriber.next(v);
7253
- subscriber.complete();
7254
- }).catch(e => subscriber.error(e));
7877
+ handler(options?.observe || 'body', this[kRequest]).subscribe((subscriber));
7255
7878
  });
7256
- this._handler = _handler;
7257
- this.options = options;
7879
+ this[kHandler] = handler;
7880
+ this[kRequest] = new HttpRequest(options?.http);
7258
7881
  this.contentId = uid(6);
7259
- this.options = options;
7260
7882
  }
7261
7883
  header(name, value) {
7262
- this._headers = this._headers || {};
7263
- this._headers[name] = value;
7884
+ this[kRequest].headers.append(name, value);
7264
7885
  return this;
7265
7886
  }
7266
- /**
7267
- * Sends the request
7268
- */
7269
- async fetch() {
7270
- const promise = this._promise || (this._promise = new Promise((resolve, reject) => {
7271
- setTimeout(() => {
7272
- this._execute().then(resolve).catch(reject);
7273
- }, 0);
7274
- }));
7275
- return await promise;
7887
+ param(name, value) {
7888
+ this[kRequest].params.append(name, value);
7889
+ return this;
7276
7890
  }
7277
- /**
7278
- * Sends the request and returns response data
7279
- */
7280
- async resolve() {
7281
- const resp = await this.fetch();
7282
- return resp.data;
7891
+ async fetch(observe) {
7892
+ return lastValueFrom(this[kHandler](observe || 'body', this[kRequest]));
7283
7893
  }
7284
7894
  with(cb) {
7285
7895
  cb(this);
7286
7896
  return this;
7287
7897
  }
7288
- binding() {
7289
- return {};
7290
- }
7291
- async _execute() {
7292
- const req = this.prepare();
7293
- return await this._handler(req);
7294
- }
7295
- }
7296
-
7297
- function mergeRawHttpRequests(target, ...other) {
7298
- let params;
7299
- const arr = [target, ...other];
7300
- let headers;
7301
- for (let i = arr.length - 1; i >= 0; i--) {
7302
- const o = arr[i];
7303
- if (o?.headers) {
7304
- headers = headers || {};
7305
- Object.assign(headers, normalizeHeaders(o.headers));
7306
- }
7307
- }
7308
- for (const o of arr) {
7309
- if (!o)
7310
- continue;
7311
- Object.assign(target, o);
7312
- if (o?.params) {
7313
- params = params || new OpraURLSearchParams();
7314
- o.params.forEach((v, n) => params?.append(n, v));
7315
- }
7316
- }
7317
- target.headers = headers;
7318
- target.params = params;
7319
- return target;
7320
7898
  }
7899
+ HttpRequestHost.kHandler = kHandler;
7900
+ HttpRequestHost.kRequest = kRequest;
7321
7901
 
7322
- class CollectionCreateRequest extends HttpRequest {
7323
- constructor(_handler, resource, data, options = {}) {
7324
- super(_handler, options);
7325
- this._handler = _handler;
7902
+ class CollectionCreateRequest extends HttpRequestHost {
7903
+ constructor(handler, resource, data, options) {
7904
+ super(handler, options);
7326
7905
  this.resource = resource;
7327
- this.data = data;
7328
- this.options = options;
7329
- }
7330
- prepare() {
7331
- const searchParams = new OpraURLSearchParams();
7332
- if (this.options.include)
7333
- searchParams.set('$include', this.options.include);
7334
- if (this.options.pick)
7335
- searchParams.set('$pick', this.options.pick);
7336
- if (this.options.omit)
7337
- searchParams.set('$omit', this.options.omit);
7338
- return mergeRawHttpRequests({
7339
- method: 'POST',
7340
- path: this.resource.name,
7341
- params: searchParams,
7342
- body: this.data,
7343
- }, this.options.http);
7344
- }
7345
- }
7346
-
7347
- class CollectionDeleteManyRequest extends HttpRequest {
7348
- constructor(_handler, resource, options = {}) {
7349
- super(_handler, options);
7350
- this._handler = _handler;
7351
- this.resource = resource;
7352
- this.options = options;
7353
- }
7354
- prepare() {
7355
- const searchParams = new OpraURLSearchParams();
7356
- if (this.options.filter)
7357
- searchParams.set('$filter', this.options.filter);
7358
- return mergeRawHttpRequests({
7359
- method: 'DELETE',
7360
- path: this.resource.name,
7361
- params: searchParams,
7362
- }, this.options.http);
7906
+ const request = this[HttpRequestHost.kRequest];
7907
+ request.method = 'POST';
7908
+ request.url = this.resource.name;
7909
+ request.body = data;
7910
+ if (options?.include)
7911
+ request.params.set('$include', options.include);
7912
+ if (options?.pick)
7913
+ request.params.set('$pick', options.pick);
7914
+ if (options?.omit)
7915
+ request.params.set('$omit', options.omit);
7363
7916
  }
7364
7917
  }
7365
7918
 
7366
- class CollectionDeleteRequest extends HttpRequest {
7367
- constructor(_handler, resource, keyValue, options = {}) {
7368
- super(_handler, options);
7369
- this._handler = _handler;
7919
+ class CollectionDeleteManyRequest extends HttpRequestHost {
7920
+ constructor(handler, resource, options) {
7921
+ super(handler, options);
7370
7922
  this.resource = resource;
7371
- this.keyValue = keyValue;
7372
- this.options = options;
7373
- }
7374
- prepare() {
7375
- if (this.keyValue == null || this.keyValue === '')
7376
- throw new TypeError('Key value required to perform "delete" request');
7377
- const path = new OpraURLPath({ resource: this.resource.name, key: this.keyValue });
7378
- return mergeRawHttpRequests({
7379
- method: 'DELETE',
7380
- path: path.toString(),
7381
- }, this.options.http);
7923
+ const request = this[HttpRequestHost.kRequest];
7924
+ request.method = 'DELETE';
7925
+ request.url = this.resource.name;
7926
+ if (options?.filter)
7927
+ request.params.set('$filter', options.filter);
7382
7928
  }
7383
7929
  }
7384
7930
 
7385
- class CollectionGetRequest extends HttpRequest {
7386
- constructor(_handler, resource, keyValue, options = {}) {
7387
- super(_handler, options);
7388
- this._handler = _handler;
7931
+ class CollectionDeleteRequest extends HttpRequestHost {
7932
+ constructor(handler, resource, id, options) {
7933
+ super(handler, options);
7389
7934
  this.resource = resource;
7390
- this.keyValue = keyValue;
7391
- this.options = options;
7392
- }
7393
- prepare() {
7394
- if (this.keyValue == null || this.keyValue === '')
7395
- throw new TypeError('Key value required to perform "get" request');
7396
- const path = new OpraURLPath({ resource: this.resource.name, key: this.keyValue });
7397
- const searchParams = new OpraURLSearchParams();
7398
- if (this.options.include)
7399
- searchParams.set('$include', this.options.include);
7400
- if (this.options.pick)
7401
- searchParams.set('$pick', this.options.pick);
7402
- if (this.options.omit)
7403
- searchParams.set('$omit', this.options.omit);
7404
- return mergeRawHttpRequests({
7405
- method: 'GET',
7406
- path: path.toString(),
7407
- params: searchParams
7408
- }, this.options.http);
7935
+ const request = this[HttpRequestHost.kRequest];
7936
+ request.method = 'DELETE';
7937
+ request.path.join({ resource: this.resource.name, key: id });
7409
7938
  }
7410
7939
  }
7411
7940
 
7412
- class CollectionSearchRequest extends HttpRequest {
7413
- constructor(_handler, resource, options = {}) {
7414
- super(_handler, options);
7415
- this._handler = _handler;
7941
+ class CollectionGetRequest extends HttpRequestHost {
7942
+ constructor(handler, resource, id, options) {
7943
+ super(handler, options);
7416
7944
  this.resource = resource;
7417
- this.options = options;
7418
- }
7419
- prepare() {
7420
- const searchParams = new OpraURLSearchParams();
7421
- if (this.options.include)
7422
- searchParams.set('$include', this.options.include);
7423
- if (this.options.pick)
7424
- searchParams.set('$pick', this.options.pick);
7425
- if (this.options.omit)
7426
- searchParams.set('$omit', this.options.omit);
7427
- if (this.options.sort)
7428
- searchParams.set('$sort', this.options.sort);
7429
- if (this.options.filter)
7430
- searchParams.set('$filter', this.options.filter);
7431
- if (this.options.limit != null)
7432
- searchParams.set('$limit', this.options.limit);
7433
- if (this.options.skip != null)
7434
- searchParams.set('$skip', this.options.skip);
7435
- if (this.options.count != null)
7436
- searchParams.set('$count', this.options.count);
7437
- if (this.options.distinct != null)
7438
- searchParams.set('$distinct', this.options.distinct);
7439
- return mergeRawHttpRequests({
7440
- method: 'GET',
7441
- path: this.resource.name,
7442
- params: searchParams
7443
- }, this.options.http);
7945
+ const request = this[HttpRequestHost.kRequest];
7946
+ request.method = 'GET';
7947
+ request.path.join({ resource: this.resource.name, key: id });
7948
+ if (options?.include)
7949
+ request.params.set('$include', options.include);
7950
+ if (options?.pick)
7951
+ request.params.set('$pick', options.pick);
7952
+ if (options?.omit)
7953
+ request.params.set('$omit', options.omit);
7444
7954
  }
7445
7955
  }
7446
7956
 
7447
- class CollectionUpdateManyRequest extends HttpRequest {
7448
- constructor(_handler, resource, data, options = {}) {
7449
- super(_handler, options);
7450
- this._handler = _handler;
7957
+ class CollectionSearchRequest extends HttpRequestHost {
7958
+ constructor(handler, resource, options) {
7959
+ super(handler, options);
7451
7960
  this.resource = resource;
7452
- this.data = data;
7453
- this.options = options;
7454
- }
7455
- prepare() {
7456
- const searchParams = new OpraURLSearchParams();
7457
- if (this.options.filter)
7458
- searchParams.set('$filter', this.options.filter);
7459
- return mergeRawHttpRequests({
7460
- method: 'PATCH',
7461
- path: this.resource.name,
7462
- params: searchParams,
7463
- body: this.data
7464
- }, this.options.http);
7961
+ const request = this[HttpRequestHost.kRequest];
7962
+ request.method = 'GET';
7963
+ request.url = this.resource.name;
7964
+ if (options?.include)
7965
+ request.params.set('$include', options.include);
7966
+ if (options?.pick)
7967
+ request.params.set('$pick', options.pick);
7968
+ if (options?.omit)
7969
+ request.params.set('$omit', options.omit);
7970
+ if (options?.sort)
7971
+ request.params.set('$sort', options.sort);
7972
+ if (options?.filter)
7973
+ request.params.set('$filter', options.filter);
7974
+ if (options?.limit != null)
7975
+ request.params.set('$limit', options.limit);
7976
+ if (options?.skip != null)
7977
+ request.params.set('$skip', options.skip);
7978
+ if (options?.count != null)
7979
+ request.params.set('$count', options.count);
7980
+ if (options?.distinct != null)
7981
+ request.params.set('$distinct', options.distinct);
7982
+ }
7983
+ }
7984
+
7985
+ class CollectionUpdateManyRequest extends HttpRequestHost {
7986
+ constructor(handler, resource, data, options) {
7987
+ super(handler, options);
7988
+ this.resource = resource;
7989
+ const request = this[HttpRequestHost.kRequest];
7990
+ request.method = 'PATCH';
7991
+ request.url = this.resource.name;
7992
+ request.body = data;
7993
+ if (options?.filter)
7994
+ request.params.set('$filter', options.filter);
7465
7995
  }
7466
7996
  }
7467
7997
 
7468
- class CollectionUpdateRequest extends HttpRequest {
7469
- constructor(_handler, resource, keyValue, data, options = {}) {
7470
- super(_handler, options);
7471
- this._handler = _handler;
7998
+ class CollectionUpdateRequest extends HttpRequestHost {
7999
+ constructor(handler, resource, id, data, options) {
8000
+ super(handler, options);
7472
8001
  this.resource = resource;
7473
- this.keyValue = keyValue;
7474
- this.data = data;
7475
- this.options = options;
7476
- }
7477
- prepare() {
7478
- if (this.keyValue == null || this.keyValue === '')
7479
- throw new TypeError('Key value required to perform "get" request');
7480
- const path = new OpraURLPath({ resource: this.resource.name, key: this.keyValue });
7481
- const searchParams = new OpraURLSearchParams();
7482
- if (this.options.include)
7483
- searchParams.set('$include', this.options.include);
7484
- if (this.options.pick)
7485
- searchParams.set('$pick', this.options.pick);
7486
- if (this.options.omit)
7487
- searchParams.set('$omit', this.options.omit);
7488
- return mergeRawHttpRequests({
7489
- method: 'PATCH',
7490
- path: path.toString(),
7491
- params: searchParams,
7492
- body: this.data
7493
- }, this.options.http);
8002
+ const request = this[HttpRequestHost.kRequest];
8003
+ request.method = 'PATCH';
8004
+ request.path.join({ resource: this.resource.name, key: id });
8005
+ request.body = data;
8006
+ if (options?.include)
8007
+ request.params.set('$include', options.include);
8008
+ if (options?.pick)
8009
+ request.params.set('$pick', options.pick);
8010
+ if (options?.omit)
8011
+ request.params.set('$omit', options.omit);
7494
8012
  }
7495
8013
  }
7496
8014
 
@@ -7502,133 +8020,68 @@ class HttpCollectionService {
7502
8020
  create(data, options) {
7503
8021
  return new CollectionCreateRequest(this._handler, this.resource, data, options);
7504
8022
  }
7505
- delete(keyValue, options) {
7506
- return new CollectionDeleteRequest(this._handler, this.resource, keyValue, options);
8023
+ delete(id, options) {
8024
+ return new CollectionDeleteRequest(this._handler, this.resource, id, options);
7507
8025
  }
7508
8026
  deleteMany(options) {
7509
8027
  return new CollectionDeleteManyRequest(this._handler, this.resource, options);
7510
8028
  }
7511
- get(keyValue, options) {
7512
- return new CollectionGetRequest(this._handler, this.resource, keyValue, options);
8029
+ get(id, options) {
8030
+ return new CollectionGetRequest(this._handler, this.resource, id, options);
7513
8031
  }
7514
8032
  search(options) {
7515
8033
  return new CollectionSearchRequest(this._handler, this.resource, options);
7516
8034
  }
7517
- update(keyValue, data, options) {
7518
- return new CollectionUpdateRequest(this._handler, this.resource, keyValue, data, options);
8035
+ update(id, data, options) {
8036
+ return new CollectionUpdateRequest(this._handler, this.resource, id, data, options);
7519
8037
  }
7520
8038
  updateMany(data, options) {
7521
8039
  return new CollectionUpdateManyRequest(this._handler, this.resource, data, options);
7522
8040
  }
7523
8041
  }
7524
8042
 
7525
- class HttpSingletonGetRequest extends HttpRequest {
7526
- constructor(_handler, resource, options = {}) {
7527
- super(_handler, options);
7528
- this._handler = _handler;
8043
+ class SingletonDeleteRequest extends HttpRequestHost {
8044
+ constructor(handler, resource, options) {
8045
+ super(handler, options);
7529
8046
  this.resource = resource;
7530
- this.options = options;
7531
- }
7532
- prepare() {
7533
- const searchParams = new URLSearchParams();
7534
- if (this.options.include)
7535
- searchParams.set('$include', '' + this.options.include);
7536
- if (this.options.pick)
7537
- searchParams.set('$pick', '' + this.options.pick);
7538
- if (this.options.omit)
7539
- searchParams.set('$omit', '' + this.options.omit);
7540
- return mergeRawHttpRequests({
7541
- method: 'GET',
7542
- path: this.resource.name,
7543
- params: searchParams
7544
- }, this.options.http);
8047
+ const request = this[HttpRequestHost.kRequest];
8048
+ request.method = 'DELETE';
8049
+ request.url = this.resource.name;
7545
8050
  }
7546
8051
  }
7547
8052
 
7548
- class HttpSingletonService {
7549
- constructor(resource, _handler) {
8053
+ class SingletonGetRequest extends HttpRequestHost {
8054
+ constructor(handler, resource, options) {
8055
+ super(handler, options);
7550
8056
  this.resource = resource;
7551
- this._handler = _handler;
7552
- }
7553
- get(options) {
7554
- return new HttpSingletonGetRequest(this._handler, this.resource, options);
8057
+ const request = this[HttpRequestHost.kRequest];
8058
+ request.method = 'GET';
8059
+ request.url = this.resource.name;
8060
+ if (options?.include)
8061
+ request.params.set('$include', options.include);
8062
+ if (options?.pick)
8063
+ request.params.set('$pick', options.pick);
8064
+ if (options?.omit)
8065
+ request.params.set('$omit', options.omit);
7555
8066
  }
7556
8067
  }
7557
8068
 
7558
- class BatchRequest extends HttpRequest {
7559
- constructor(_handler, requests, options = {}) {
7560
- super(_handler, options);
8069
+ class HttpSingletonService {
8070
+ constructor(resource, _handler) {
8071
+ this.resource = resource;
7561
8072
  this._handler = _handler;
7562
- this.requests = requests;
7563
- this.options = options;
7564
- this._results = new WeakMap();
7565
- this._listeners = new Set();
7566
- requests.forEach(request => {
7567
- // Overwrite the _execute method
7568
- Object.defineProperty(request, '_execute', {
7569
- writable: true,
7570
- enumerable: false,
7571
- configurable: true,
7572
- value: () => {
7573
- return new Promise((resolve, reject) => {
7574
- const x = this._results.get(request);
7575
- if (x) {
7576
- if (x.error)
7577
- return reject(x.error);
7578
- return resolve(x.response);
7579
- }
7580
- const callback = (error, response) => {
7581
- this._listeners.delete(callback);
7582
- if (error)
7583
- return reject(error);
7584
- resolve(response);
7585
- };
7586
- this._listeners.add(callback);
7587
- });
7588
- }
7589
- });
7590
- });
7591
8073
  }
7592
- prepare() {
7593
- const batch = this._buildBatchMultipart(this);
7594
- const headers = {
7595
- 'content-type': 'multipart/mixed;boundary=' + batch.boundary
7596
- };
7597
- return mergeRawHttpRequests({
7598
- method: 'POST',
7599
- path: '/$batch',
7600
- headers,
7601
- body: batch.stream()
7602
- }, this.options.http);
7603
- }
7604
- _buildBatchMultipart(batch) {
7605
- const multipart = new BatchMultipart();
7606
- for (const req of batch.requests) {
7607
- const prepared = req.prepare();
7608
- if (req instanceof BatchRequest) {
7609
- const subMultipart = this._buildBatchMultipart(req);
7610
- multipart.addBatch(subMultipart);
7611
- continue;
7612
- }
7613
- multipart.addRequestPart({
7614
- method: prepared.method,
7615
- url: prepared.path,
7616
- headers: prepared.headers,
7617
- data: prepared.body
7618
- });
7619
- }
7620
- return multipart;
8074
+ get(options) {
8075
+ return new SingletonGetRequest(this._handler, this.resource, options);
7621
8076
  }
7622
- async _execute() {
7623
- const req = this.prepare();
7624
- const resp = await this._handler(req);
7625
- return resp;
8077
+ delete(options) {
8078
+ return new SingletonDeleteRequest(this._handler, this.resource, options);
7626
8079
  }
7627
8080
  }
7628
8081
 
7629
8082
  const documentCache = new Map();
7630
8083
  const documentResolverCaches = new Map();
7631
- class OpraHttpClient {
8084
+ class OpraHttpClientBase {
7632
8085
  constructor(serviceUrl, options) {
7633
8086
  this._serviceUrl = serviceUrl;
7634
8087
  this._metadata = options?.document;
@@ -7637,7 +8090,13 @@ class OpraHttpClient {
7637
8090
  if (document)
7638
8091
  this._metadata = document;
7639
8092
  }
7640
- this.defaults = options?.defaults || {};
8093
+ this.defaults = {
8094
+ ...options?.defaults,
8095
+ headers: options?.defaults?.headers instanceof HttpHeaders
8096
+ ? options?.defaults?.headers : new HttpHeaders(options?.defaults?.headers),
8097
+ params: options?.defaults?.params instanceof HttpParams
8098
+ ? options?.defaults?.params : new HttpParams(options?.defaults?.headers)
8099
+ };
7641
8100
  }
7642
8101
  get serviceUrl() {
7643
8102
  return this._serviceUrl;
@@ -7665,17 +8124,17 @@ class OpraHttpClient {
7665
8124
  .catch(() => void 0)
7666
8125
  .finally(() => documentResolverCaches.delete(cacheName));
7667
8126
  }
7668
- batch(requests) {
7669
- this._assertMetadata();
7670
- return new BatchRequest(req => this._handleRequest(req), requests);
7671
- }
8127
+ // batch(requests: HttpRequestHost<any>[]): BatchRequest {
8128
+ // this._assertMetadata();
8129
+ // return new BatchRequest(request => this._sendRequest('response', request, requests);
8130
+ // }
7672
8131
  collection(name) {
7673
8132
  this._assertMetadata();
7674
8133
  // If name argument is a class, we extract name from the class
7675
8134
  if (typeof name === 'function')
7676
8135
  name = name.name;
7677
8136
  const resource = this.metadata.getCollectionResource(name);
7678
- return new HttpCollectionService(resource, req => this._handleRequest(req));
8137
+ return new HttpCollectionService(resource, this._sendRequest.bind(this));
7679
8138
  }
7680
8139
  singleton(name) {
7681
8140
  this._assertMetadata();
@@ -7683,87 +8142,138 @@ class OpraHttpClient {
7683
8142
  if (typeof name === 'function')
7684
8143
  name = name.name;
7685
8144
  const resource = this.metadata.getSingletonResource(name);
7686
- return new HttpSingletonService(resource, req => this._handleRequest(req));
8145
+ return new HttpSingletonService(resource, this._sendRequest.bind(this));
7687
8146
  }
7688
8147
  async _resolveMetadata() {
7689
- const resp = await this._handleRequest({
8148
+ const body = await lastValueFrom(this._sendRequest('body', new HttpRequest({
7690
8149
  method: 'GET',
7691
- path: '/$metadata',
7692
- headers: { 'accept': 'application/json' }
7693
- });
7694
- this._metadata = new OpraDocument(resp.data);
7695
- }
7696
- async _handleRequest(req) {
7697
- mergeRawHttpRequests(req, this.defaults);
7698
- let url = joinPath(this.serviceUrl, req.path);
7699
- if (req.params)
7700
- url += '?' + req.params.toString();
7701
- if (req.body) {
7702
- if (typeof req.body === 'object') {
7703
- if (!(isReadable(req.body) || isReadableStream(req.body) || Buffer.isBuffer(req.body))) {
7704
- if (!req.headers?.['content-type']) {
7705
- req.headers = req.headers || {};
7706
- req.headers['content-type'] = 'application/json';
8150
+ url: '$metadata',
8151
+ headers: new HttpHeaders({ 'accept': 'application/json' })
8152
+ })));
8153
+ this._metadata = new OpraDocument(body);
8154
+ }
8155
+ _sendRequest(observe, request) {
8156
+ return new Observable(subscriber => {
8157
+ try {
8158
+ request.inset(this.defaults);
8159
+ const url = request.url.includes('://') ? request.url : joinPath(this.serviceUrl, request.url);
8160
+ let body;
8161
+ if (request.body) {
8162
+ let contentType = request.headers.get('Content-Type');
8163
+ if (typeof request.body === 'string' || typeof request.body === 'number' || typeof request.body === 'boolean') {
8164
+ contentType = 'text/plain;charset=UTF-8"';
8165
+ body = String(request.body);
8166
+ request.headers.delete('Content-Size');
8167
+ delete request.duplex;
8168
+ }
8169
+ else if (isReadableStreamLike(request.body)) {
8170
+ contentType = 'application/octet-stream';
8171
+ body = request.body;
8172
+ request.duplex = 'half';
8173
+ }
8174
+ else if (isReadable(request.body)) {
8175
+ contentType = 'application/octet-stream';
8176
+ body = Readable.toWeb(request.body);
8177
+ request.duplex = 'half';
8178
+ }
8179
+ else if (Buffer.isBuffer(request.body)) {
8180
+ contentType = 'application/octet-stream';
8181
+ body = request.body;
8182
+ request.headers.set('Content-Size', request.body.length);
8183
+ delete request.duplex;
7707
8184
  }
7708
- req.body = JSON.stringify(req.body);
8185
+ else if (isBlob(request.body)) {
8186
+ contentType = request.body.type || 'application/octet-stream';
8187
+ body = request.body;
8188
+ request.headers.set('Content-Size', request.body.length);
8189
+ delete request.duplex;
8190
+ }
8191
+ else {
8192
+ contentType = 'application/json';
8193
+ body = JSON.stringify(request.body);
8194
+ request.headers.delete('Content-Size');
8195
+ delete request.duplex;
8196
+ }
8197
+ if (!request.headers.has('Content-Type') && contentType)
8198
+ request.headers.set('Content-Type', contentType);
8199
+ request.body = body;
7709
8200
  }
8201
+ this._fetch(url, request)
8202
+ .then(response => this._handleResponse(observe, subscriber, request, response))
8203
+ .catch(error => subscriber.error(error));
8204
+ if (observe === 'events')
8205
+ subscriber.next({ event: 'sent', request });
7710
8206
  }
7711
- }
7712
- return this._fetch(url, req);
7713
- }
7714
- async _fetch(url, req) {
7715
- const resp = await fetch(url, req);
7716
- let data;
7717
- if (resp.body) {
7718
- if (JSON_CONTENT_TYPE_PATTERN.test(resp.headers.get('Content-Type') || '')) {
7719
- data = await resp.json();
7720
- if (typeof data === 'string')
7721
- data = JSON.parse(data);
8207
+ catch (error) {
8208
+ subscriber.error(error);
7722
8209
  }
7723
- else if (TEXT_CONTENT_TYPE_PATTERN.test(resp.headers.get('Content-Type') || ''))
7724
- data = await resp.text();
7725
- else if (FORMDATA_CONTENT_TYPE_PATTERN.test(resp.headers.get('Content-Type') || ''))
7726
- data = await resp.formData();
7727
- else
7728
- data = await resp.arrayBuffer();
7729
- }
7730
- if (resp.status >= 400 && resp.status < 600) {
7731
- throw new ClientError({
7732
- message: resp.status + ' ' + resp.statusText,
7733
- status: resp.status,
7734
- issues: data?.errors
8210
+ });
8211
+ }
8212
+ _fetch(url, init = {}) {
8213
+ return fetch(url, init);
8214
+ }
8215
+ _createResponse(init) {
8216
+ return new HttpResponse(init);
8217
+ }
8218
+ _handleResponse(observe, subscriber, request, fetchResponse) {
8219
+ const headers = new HttpHeaders(fetchResponse.headers);
8220
+ if (observe === 'events') {
8221
+ const response = this._createResponse({
8222
+ url: fetchResponse.url,
8223
+ headers,
8224
+ status: fetchResponse.status,
8225
+ statusText: fetchResponse.statusText,
8226
+ hasBody: !!fetchResponse.body
7735
8227
  });
8228
+ subscriber.next({ event: 'headers-received', request, response });
7736
8229
  }
7737
- const out = {
7738
- get headers() {
7739
- return resp.headers;
7740
- },
7741
- get ok() {
7742
- return resp.ok;
7743
- },
7744
- get redirected() {
7745
- return resp.redirected;
7746
- },
7747
- get status() {
7748
- return resp.status;
7749
- },
7750
- get statusText() {
7751
- return resp.statusText;
7752
- },
7753
- get type() {
7754
- return resp.type;
7755
- },
7756
- get url() {
7757
- return resp.url;
7758
- },
7759
- get contentId() {
7760
- return resp.headers.get('Content-ID');
7761
- },
7762
- get data() {
7763
- return data;
8230
+ Promise
8231
+ .resolve(fetchResponse.body)
8232
+ .then(async (inputStream) => {
8233
+ if (!inputStream)
8234
+ return;
8235
+ if (JSON_CONTENT_TYPE_PATTERN.test(fetchResponse.headers.get('Content-Type') || '')) {
8236
+ const body = await fetchResponse.json();
8237
+ if (typeof body === 'string')
8238
+ return JSON.parse(body);
8239
+ return body;
7764
8240
  }
7765
- };
7766
- return out;
8241
+ if (TEXT_CONTENT_TYPE_PATTERN.test(fetchResponse.headers.get('Content-Type') || ''))
8242
+ return await fetchResponse.text();
8243
+ if (FORMDATA_CONTENT_TYPE_PATTERN.test(fetchResponse.headers.get('Content-Type') || ''))
8244
+ return await fetchResponse.formData();
8245
+ const buf = await fetchResponse.arrayBuffer();
8246
+ return buf.byteLength ? buf : undefined;
8247
+ })
8248
+ .then(body => {
8249
+ if (fetchResponse.status >= 400 && fetchResponse.status < 600) {
8250
+ subscriber.error(new ClientError({
8251
+ message: fetchResponse.status + ' ' + fetchResponse.statusText,
8252
+ status: fetchResponse.status,
8253
+ issues: body?.errors
8254
+ }));
8255
+ subscriber.complete();
8256
+ return;
8257
+ }
8258
+ if (observe === 'body') {
8259
+ subscriber.next(body);
8260
+ }
8261
+ else {
8262
+ const response = this._createResponse({
8263
+ url: fetchResponse.url,
8264
+ headers,
8265
+ status: fetchResponse.status,
8266
+ statusText: fetchResponse.statusText,
8267
+ body
8268
+ });
8269
+ if (observe === 'events')
8270
+ subscriber.next({ event: 'response', request, response });
8271
+ else
8272
+ subscriber.next(response);
8273
+ }
8274
+ subscriber.complete();
8275
+ })
8276
+ .catch(error => subscriber.error(error));
7767
8277
  }
7768
8278
  _assertMetadata() {
7769
8279
  if (!this._metadata)
@@ -7776,5 +8286,7 @@ class OpraHttpClient {
7776
8286
  return client;
7777
8287
  }
7778
8288
  }
8289
+ class OpraHttpClient extends OpraHttpClientBase {
8290
+ }
7779
8291
 
7780
- export { $and, $arithmetic, $array, $date, $eq, $field, $gt, $gte, $ilike, $in, $like, $lt, $lte, $ne, $notILike, $notIn, $notLike, $number, $or, $paren, $time, ArithmeticExpression, ArithmeticExpressionItem, ArrayExpression, Ast, BadRequestError, BaseI18n, BatchMultipart, BatchRequest, BooleanLiteral, COMPLEXTYPE_FIELDS, ClientError, CollectionCountQuery, CollectionCreateQuery, CollectionCreateRequest, CollectionDeleteManyQuery, CollectionDeleteManyRequest, CollectionDeleteQuery, CollectionDeleteRequest, CollectionGetQuery, CollectionGetRequest, CollectionResourceInfo, CollectionSearchQuery, CollectionSearchRequest, CollectionUpdateManyQuery, CollectionUpdateManyRequest, CollectionUpdateQuery, CollectionUpdateRequest, ComparisonExpression, ComplexType, ContainerResourceInfo, DATATYPE_METADATA, DataType, DateLiteral, DocumentBuilder, Expression, FailedDependencyError, FieldGetQuery, FilterTreeVisitor, ForbiddenError, HttpCollectionService, HttpHeaders, HttpSingletonGetRequest, HttpSingletonService, HttpStatus, I18n, IGNORE_RESOLVER_METHOD, InternalServerError, IssueSeverity, Literal, LogicalExpression, MAPPED_TYPE_METADATA, MethodNotAllowedError, MixinType, NotAcceptableError, NotFoundError, NullLiteral, NumberLiteral, OmitType, OprCollectionResource, OprComplexType, OprCreateResolver, OprDeleteManyResolver, OprDeleteResolver, OprField, OprGetResolver, OprSearchResolver, OprSingletonResource, OprUpdateManyResolver, OprUpdateResolver, OpraDocument, OpraErrorListener, OpraException, OpraHttpClient, OpraSchema, OpraURL, OpraURLPath, OpraURLPathComponent, OpraURLSearchParams, ParenthesesExpression, PickType, QualifiedIdentifier, RESOLVER_METADATA, RESOURCE_METADATA, ResourceConflictError, ResourceInfo, ResourceNotFoundError, ResponsiveMap, SimpleType, SingletonGetQuery, SingletonResourceInfo, StringLiteral, Term, TimeLiteral, UnauthorizedError, UnionType, UnprocessableEntityError, collectionMethods, decodePathComponent, encodePathComponent, extractDataTypeSchema, extractResourceSchema, i18n, isBlob, isChildFieldQuery, isFormData, isReadable, isReadableStream, isURL, isUrl, joinPath, normalizeHeaders, normalizePath, parseFilter, pathToTree$1 as pathToTree, singletonMethods, translate, typeGuards, wrapException };
8292
+ export { $and, $arithmetic, $array, $date, $eq, $field, $gt, $gte, $ilike, $in, $like, $lt, $lte, $ne, $notILike, $notIn, $notLike, $number, $or, $paren, $time, ArithmeticExpression, ArithmeticExpressionItem, ArrayExpression, Ast, BadRequestError, BaseI18n, BatchMultipart, BooleanCodec, BooleanLiteral, COMPLEXTYPE_FIELDS, ClientError, CollectionCountQuery, CollectionCreateQuery, CollectionCreateRequest, CollectionDeleteManyQuery, CollectionDeleteManyRequest, CollectionDeleteQuery, CollectionDeleteRequest, CollectionGetQuery, CollectionGetRequest, CollectionResourceInfo, CollectionSearchQuery, CollectionSearchRequest, CollectionUpdateManyQuery, CollectionUpdateManyRequest, CollectionUpdateQuery, CollectionUpdateRequest, ComparisonExpression, ComplexType, ContainerResourceInfo, DATATYPE_METADATA, DataType, DateCodec, DateLiteral, DocumentBuilder, Expression, FailedDependencyError, FieldGetQuery, FilterCodec, FilterTreeVisitor, ForbiddenError, HttpCollectionService, HttpHeaderCodes, HttpHeaders, HttpParamCodec, HttpParams, HttpRequest, HttpRequestHost, HttpRequestNode, HttpResponse, HttpSingletonService, HttpStatusCodes, I18n, IGNORE_RESOLVER_METHOD, IntegerCodec, InternalServerError, IssueSeverity, Literal, LogicalExpression, MAPPED_TYPE_METADATA, MethodNotAllowedError, MixinType, NotAcceptableError, NotFoundError, NullLiteral, NumberCodec, NumberLiteral, OmitType, OprCollectionResource, OprComplexType, OprCreateResolver, OprDeleteManyResolver, OprDeleteResolver, OprField, OprGetResolver, OprSearchResolver, OprSingletonResource, OprUpdateManyResolver, OprUpdateResolver, OpraDocument, OpraErrorListener, OpraException, OpraHttpClient, OpraHttpClientBase, OpraSchema, OpraURL, OpraURLPath, OpraURLPathComponent, OpraURLSearchParams, ParenthesesExpression, PickType, QualifiedIdentifier, RESOLVER_METADATA, RESOURCE_METADATA, ResourceConflictError, ResourceInfo, ResourceNotFoundError, ResponsiveMap, SimpleType, SingletonDeleteRequest, SingletonGetQuery, SingletonGetRequest, SingletonResourceInfo, StringCodec, StringLiteral, Term, TimeLiteral, UnauthorizedError, UnionType, UnprocessableEntityError, collectionMethods, decodePathComponent, encodePathComponent, extractDataTypeSchema, extractResourceSchema, i18n, isBlob, isChildFieldQuery, isFormData, isReadable, isReadableStream, isURL, isUrl, joinPath, normalizeHeaders, normalizePath, parseFilter, pathToTree$1 as pathToTree, singletonMethods, translate, typeGuards, wrapException };