angular-in-memory-web-api
Version:
An in-memory web api for Angular demos and tests
1 lines • 100 kB
Source Map (JSON)
{"version":3,"file":"angular-in-memory-web-api.mjs","sources":["../../../../../../darwin_arm64-fastbuild-ST-2d99d9656325/bin/packages/misc/angular-in-memory-web-api/src/delay-response.ts","../../../../../../darwin_arm64-fastbuild-ST-2d99d9656325/bin/packages/misc/angular-in-memory-web-api/src/http-status-codes.ts","../../../../../../darwin_arm64-fastbuild-ST-2d99d9656325/bin/packages/misc/angular-in-memory-web-api/src/interfaces.ts","../../../../../../darwin_arm64-fastbuild-ST-2d99d9656325/bin/packages/misc/angular-in-memory-web-api/src/backend-service.ts","../../../../../../darwin_arm64-fastbuild-ST-2d99d9656325/bin/packages/misc/angular-in-memory-web-api/src/http-client-backend-service.ts","../../../../../../darwin_arm64-fastbuild-ST-2d99d9656325/bin/packages/misc/angular-in-memory-web-api/src/http-client-in-memory-web-api-module.ts","../../../../../../darwin_arm64-fastbuild-ST-2d99d9656325/bin/packages/misc/angular-in-memory-web-api/src/in-memory-web-api-module.ts"],"sourcesContent":["/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {Observable} from 'rxjs';\n\n// Replaces use of RxJS delay. See v0.5.4.\n/** adds specified delay (in ms) to both next and error channels of the response observable */\nexport function delayResponse<T>(response$: Observable<T>, delayMs: number): Observable<T> {\n return new Observable<T>((observer) => {\n let completePending = false;\n let nextPending = false;\n const subscription = response$.subscribe(\n (value) => {\n nextPending = true;\n setTimeout(() => {\n observer.next(value);\n if (completePending) {\n observer.complete();\n }\n }, delayMs);\n },\n (error) => setTimeout(() => observer.error(error), delayMs),\n () => {\n completePending = true;\n if (!nextPending) {\n observer.complete();\n }\n },\n );\n return () => {\n return subscription.unsubscribe();\n };\n });\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nexport const STATUS = {\n CONTINUE: 100,\n SWITCHING_PROTOCOLS: 101,\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NON_AUTHORITATIVE_INFORMATION: 203,\n NO_CONTENT: 204,\n RESET_CONTENT: 205,\n PARTIAL_CONTENT: 206,\n MULTIPLE_CHOICES: 300,\n MOVED_PERMANTENTLY: 301,\n FOUND: 302,\n SEE_OTHER: 303,\n NOT_MODIFIED: 304,\n USE_PROXY: 305,\n TEMPORARY_REDIRECT: 307,\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n PROXY_AUTHENTICATION_REQUIRED: 407,\n REQUEST_TIMEOUT: 408,\n CONFLICT: 409,\n GONE: 410,\n LENGTH_REQUIRED: 411,\n PRECONDITION_FAILED: 412,\n PAYLOAD_TO_LARGE: 413,\n URI_TOO_LONG: 414,\n UNSUPPORTED_MEDIA_TYPE: 415,\n RANGE_NOT_SATISFIABLE: 416,\n EXPECTATION_FAILED: 417,\n IM_A_TEAPOT: 418,\n UPGRADE_REQUIRED: 426,\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n HTTP_VERSION_NOT_SUPPORTED: 505,\n PROCESSING: 102,\n MULTI_STATUS: 207,\n IM_USED: 226,\n PERMANENT_REDIRECT: 308,\n UNPROCESSABLE_ENTRY: 422,\n LOCKED: 423,\n FAILED_DEPENDENCY: 424,\n PRECONDITION_REQUIRED: 428,\n TOO_MANY_REQUESTS: 429,\n REQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n UNAVAILABLE_FOR_LEGAL_REASONS: 451,\n VARIANT_ALSO_NEGOTIATES: 506,\n INSUFFICIENT_STORAGE: 507,\n NETWORK_AUTHENTICATION_REQUIRED: 511,\n};\n\nexport const STATUS_CODE_INFO: {\n [key: string]: {\n code: number;\n text: string;\n description: string;\n spec_title: string;\n spec_href: string;\n };\n} = {\n '100': {\n 'code': 100,\n 'text': 'Continue',\n 'description':\n '\"The initial part of a request has been received and has not yet been rejected by the server.\"',\n 'spec_title': 'RFC7231#6.2.1',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.2.1',\n },\n '101': {\n 'code': 101,\n 'text': 'Switching Protocols',\n 'description':\n '\"The server understands and is willing to comply with the client\\'s request, via the Upgrade header field, for a change in the application protocol being used on this connection.\"',\n 'spec_title': 'RFC7231#6.2.2',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.2.2',\n },\n '200': {\n 'code': 200,\n 'text': 'OK',\n 'description': '\"The request has succeeded.\"',\n 'spec_title': 'RFC7231#6.3.1',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.1',\n },\n '201': {\n 'code': 201,\n 'text': 'Created',\n 'description':\n '\"The request has been fulfilled and has resulted in one or more new resources being created.\"',\n 'spec_title': 'RFC7231#6.3.2',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.2',\n },\n '202': {\n 'code': 202,\n 'text': 'Accepted',\n 'description':\n '\"The request has been accepted for processing, but the processing has not been completed.\"',\n 'spec_title': 'RFC7231#6.3.3',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.3',\n },\n '203': {\n 'code': 203,\n 'text': 'Non-Authoritative Information',\n 'description':\n '\"The request was successful but the enclosed payload has been modified from that of the origin server\\'s 200 (OK) response by a transforming proxy.\"',\n 'spec_title': 'RFC7231#6.3.4',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.4',\n },\n '204': {\n 'code': 204,\n 'text': 'No Content',\n 'description':\n '\"The server has successfully fulfilled the request and that there is no additional content to send in the response payload body.\"',\n 'spec_title': 'RFC7231#6.3.5',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.5',\n },\n '205': {\n 'code': 205,\n 'text': 'Reset Content',\n 'description':\n '\"The server has fulfilled the request and desires that the user agent reset the \"document view\", which caused the request to be sent, to its original state as received from the origin server.\"',\n 'spec_title': 'RFC7231#6.3.6',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.6',\n },\n '206': {\n 'code': 206,\n 'text': 'Partial Content',\n 'description':\n '\"The server is successfully fulfilling a range request for the target resource by transferring one or more parts of the selected representation that correspond to the satisfiable ranges found in the requests\\'s Range header field.\"',\n 'spec_title': 'RFC7233#4.1',\n 'spec_href': 'https://tools.ietf.org/html/rfc7233#section-4.1',\n },\n '300': {\n 'code': 300,\n 'text': 'Multiple Choices',\n 'description':\n '\"The target resource has more than one representation, each with its own more specific identifier, and information about the alternatives is being provided so that the user (or user agent) can select a preferred representation by redirecting its request to one or more of those identifiers.\"',\n 'spec_title': 'RFC7231#6.4.1',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.4.1',\n },\n '301': {\n 'code': 301,\n 'text': 'Moved Permanently',\n 'description':\n '\"The target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs.\"',\n 'spec_title': 'RFC7231#6.4.2',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.4.2',\n },\n '302': {\n 'code': 302,\n 'text': 'Found',\n 'description': '\"The target resource resides temporarily under a different URI.\"',\n 'spec_title': 'RFC7231#6.4.3',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.4.3',\n },\n '303': {\n 'code': 303,\n 'text': 'See Other',\n 'description':\n '\"The server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, that is intended to provide an indirect response to the original request.\"',\n 'spec_title': 'RFC7231#6.4.4',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.4.4',\n },\n '304': {\n 'code': 304,\n 'text': 'Not Modified',\n 'description':\n '\"A conditional GET request has been received and would have resulted in a 200 (OK) response if it were not for the fact that the condition has evaluated to false.\"',\n 'spec_title': 'RFC7232#4.1',\n 'spec_href': 'https://tools.ietf.org/html/rfc7232#section-4.1',\n },\n '305': {\n 'code': 305,\n 'text': 'Use Proxy',\n 'description': '*deprecated*',\n 'spec_title': 'RFC7231#6.4.5',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.4.5',\n },\n '307': {\n 'code': 307,\n 'text': 'Temporary Redirect',\n 'description':\n '\"The target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI.\"',\n 'spec_title': 'RFC7231#6.4.7',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.4.7',\n },\n '400': {\n 'code': 400,\n 'text': 'Bad Request',\n 'description':\n '\"The server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process.\"',\n 'spec_title': 'RFC7231#6.5.1',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.1',\n },\n '401': {\n 'code': 401,\n 'text': 'Unauthorized',\n 'description':\n '\"The request has not been applied because it lacks valid authentication credentials for the target resource.\"',\n 'spec_title': 'RFC7235#6.3.1',\n 'spec_href': 'https://tools.ietf.org/html/rfc7235#section-3.1',\n },\n '402': {\n 'code': 402,\n 'text': 'Payment Required',\n 'description': '*reserved*',\n 'spec_title': 'RFC7231#6.5.2',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.2',\n },\n '403': {\n 'code': 403,\n 'text': 'Forbidden',\n 'description': '\"The server understood the request but refuses to authorize it.\"',\n 'spec_title': 'RFC7231#6.5.3',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.3',\n },\n '404': {\n 'code': 404,\n 'text': 'Not Found',\n 'description':\n '\"The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.\"',\n 'spec_title': 'RFC7231#6.5.4',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.4',\n },\n '405': {\n 'code': 405,\n 'text': 'Method Not Allowed',\n 'description':\n '\"The method specified in the request-line is known by the origin server but not supported by the target resource.\"',\n 'spec_title': 'RFC7231#6.5.5',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.5',\n },\n '406': {\n 'code': 406,\n 'text': 'Not Acceptable',\n 'description':\n '\"The target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation.\"',\n 'spec_title': 'RFC7231#6.5.6',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.6',\n },\n '407': {\n 'code': 407,\n 'text': 'Proxy Authentication Required',\n 'description': '\"The client needs to authenticate itself in order to use a proxy.\"',\n 'spec_title': 'RFC7231#6.3.2',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.3.2',\n },\n '408': {\n 'code': 408,\n 'text': 'Request Timeout',\n 'description':\n '\"The server did not receive a complete request message within the time that it was prepared to wait.\"',\n 'spec_title': 'RFC7231#6.5.7',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.7',\n },\n '409': {\n 'code': 409,\n 'text': 'Conflict',\n 'description':\n '\"The request could not be completed due to a conflict with the current state of the resource.\"',\n 'spec_title': 'RFC7231#6.5.8',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.8',\n },\n '410': {\n 'code': 410,\n 'text': 'Gone',\n 'description':\n '\"Access to the target resource is no longer available at the origin server and that this condition is likely to be permanent.\"',\n 'spec_title': 'RFC7231#6.5.9',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.9',\n },\n '411': {\n 'code': 411,\n 'text': 'Length Required',\n 'description': '\"The server refuses to accept the request without a defined Content-Length.\"',\n 'spec_title': 'RFC7231#6.5.10',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.10',\n },\n '412': {\n 'code': 412,\n 'text': 'Precondition Failed',\n 'description':\n '\"One or more preconditions given in the request header fields evaluated to false when tested on the server.\"',\n 'spec_title': 'RFC7232#4.2',\n 'spec_href': 'https://tools.ietf.org/html/rfc7232#section-4.2',\n },\n '413': {\n 'code': 413,\n 'text': 'Payload Too Large',\n 'description':\n '\"The server is refusing to process a request because the request payload is larger than the server is willing or able to process.\"',\n 'spec_title': 'RFC7231#6.5.11',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.11',\n },\n '414': {\n 'code': 414,\n 'text': 'URI Too Long',\n 'description':\n '\"The server is refusing to service the request because the request-target is longer than the server is willing to interpret.\"',\n 'spec_title': 'RFC7231#6.5.12',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.12',\n },\n '415': {\n 'code': 415,\n 'text': 'Unsupported Media Type',\n 'description':\n '\"The origin server is refusing to service the request because the payload is in a format not supported by the target resource for this method.\"',\n 'spec_title': 'RFC7231#6.5.13',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.13',\n },\n '416': {\n 'code': 416,\n 'text': 'Range Not Satisfiable',\n 'description':\n '\"None of the ranges in the request\\'s Range header field overlap the current extent of the selected resource or that the set of ranges requested has been rejected due to invalid ranges or an excessive request of small or overlapping ranges.\"',\n 'spec_title': 'RFC7233#4.4',\n 'spec_href': 'https://tools.ietf.org/html/rfc7233#section-4.4',\n },\n '417': {\n 'code': 417,\n 'text': 'Expectation Failed',\n 'description':\n '\"The expectation given in the request\\'s Expect header field could not be met by at least one of the inbound servers.\"',\n 'spec_title': 'RFC7231#6.5.14',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.14',\n },\n '418': {\n 'code': 418,\n 'text': \"I'm a teapot\",\n 'description': '\"1988 April Fools Joke. Returned by tea pots requested to brew coffee.\"',\n 'spec_title': 'RFC 2324',\n 'spec_href': 'https://tools.ietf.org/html/rfc2324',\n },\n '426': {\n 'code': 426,\n 'text': 'Upgrade Required',\n 'description':\n '\"The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol.\"',\n 'spec_title': 'RFC7231#6.5.15',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.5.15',\n },\n '500': {\n 'code': 500,\n 'text': 'Internal Server Error',\n 'description':\n '\"The server encountered an unexpected condition that prevented it from fulfilling the request.\"',\n 'spec_title': 'RFC7231#6.6.1',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.6.1',\n },\n '501': {\n 'code': 501,\n 'text': 'Not Implemented',\n 'description':\n '\"The server does not support the functionality required to fulfill the request.\"',\n 'spec_title': 'RFC7231#6.6.2',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.6.2',\n },\n '502': {\n 'code': 502,\n 'text': 'Bad Gateway',\n 'description':\n '\"The server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.\"',\n 'spec_title': 'RFC7231#6.6.3',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.6.3',\n },\n '503': {\n 'code': 503,\n 'text': 'Service Unavailable',\n 'description':\n '\"The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay.\"',\n 'spec_title': 'RFC7231#6.6.4',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.6.4',\n },\n '504': {\n 'code': 504,\n 'text': 'Gateway Time-out',\n 'description':\n '\"The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request.\"',\n 'spec_title': 'RFC7231#6.6.5',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.6.5',\n },\n '505': {\n 'code': 505,\n 'text': 'HTTP Version Not Supported',\n 'description':\n '\"The server does not support, or refuses to support, the protocol version that was used in the request message.\"',\n 'spec_title': 'RFC7231#6.6.6',\n 'spec_href': 'https://tools.ietf.org/html/rfc7231#section-6.6.6',\n },\n '102': {\n 'code': 102,\n 'text': 'Processing',\n 'description':\n '\"An interim response to inform the client that the server has accepted the complete request, but has not yet completed it.\"',\n 'spec_title': 'RFC5218#10.1',\n 'spec_href': 'https://tools.ietf.org/html/rfc2518#section-10.1',\n },\n '207': {\n 'code': 207,\n 'text': 'Multi-Status',\n 'description': '\"Status for multiple independent operations.\"',\n 'spec_title': 'RFC5218#10.2',\n 'spec_href': 'https://tools.ietf.org/html/rfc2518#section-10.2',\n },\n '226': {\n 'code': 226,\n 'text': 'IM Used',\n 'description':\n '\"The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.\"',\n 'spec_title': 'RFC3229#10.4.1',\n 'spec_href': 'https://tools.ietf.org/html/rfc3229#section-10.4.1',\n },\n '308': {\n 'code': 308,\n 'text': 'Permanent Redirect',\n 'description':\n '\"The target resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. [...] This status code is similar to 301 Moved Permanently (Section 7.3.2 of rfc7231), except that it does not allow rewriting the request method from POST to GET.\"',\n 'spec_title': 'RFC7238',\n 'spec_href': 'https://tools.ietf.org/html/rfc7238',\n },\n '422': {\n 'code': 422,\n 'text': 'Unprocessable Entity',\n 'description':\n '\"The server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions.\"',\n 'spec_title': 'RFC5218#10.3',\n 'spec_href': 'https://tools.ietf.org/html/rfc2518#section-10.3',\n },\n '423': {\n 'code': 423,\n 'text': 'Locked',\n 'description': '\"The source or destination resource of a method is locked.\"',\n 'spec_title': 'RFC5218#10.4',\n 'spec_href': 'https://tools.ietf.org/html/rfc2518#section-10.4',\n },\n '424': {\n 'code': 424,\n 'text': 'Failed Dependency',\n 'description':\n '\"The method could not be performed on the resource because the requested action depended on another action and that action failed.\"',\n 'spec_title': 'RFC5218#10.5',\n 'spec_href': 'https://tools.ietf.org/html/rfc2518#section-10.5',\n },\n '428': {\n 'code': 428,\n 'text': 'Precondition Required',\n 'description': '\"The origin server requires the request to be conditional.\"',\n 'spec_title': 'RFC6585#3',\n 'spec_href': 'https://tools.ietf.org/html/rfc6585#section-3',\n },\n '429': {\n 'code': 429,\n 'text': 'Too Many Requests',\n 'description':\n '\"The user has sent too many requests in a given amount of time (\"rate limiting\").\"',\n 'spec_title': 'RFC6585#4',\n 'spec_href': 'https://tools.ietf.org/html/rfc6585#section-4',\n },\n '431': {\n 'code': 431,\n 'text': 'Request Header Fields Too Large',\n 'description':\n '\"The server is unwilling to process the request because its header fields are too large.\"',\n 'spec_title': 'RFC6585#5',\n 'spec_href': 'https://tools.ietf.org/html/rfc6585#section-5',\n },\n '451': {\n 'code': 451,\n 'text': 'Unavailable For Legal Reasons',\n 'description': '\"The server is denying access to the resource in response to a legal demand.\"',\n 'spec_title': 'draft-ietf-httpbis-legally-restricted-status',\n 'spec_href': 'https://tools.ietf.org/html/draft-ietf-httpbis-legally-restricted-status',\n },\n '506': {\n 'code': 506,\n 'text': 'Variant Also Negotiates',\n 'description':\n '\"The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.\"',\n 'spec_title': 'RFC2295#8.1',\n 'spec_href': 'https://tools.ietf.org/html/rfc2295#section-8.1',\n },\n '507': {\n 'code': 507,\n 'text': 'Insufficient Storage',\n 'description':\n 'The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.\"',\n 'spec_title': 'RFC5218#10.6',\n 'spec_href': 'https://tools.ietf.org/html/rfc2518#section-10.6',\n },\n '511': {\n 'code': 511,\n 'text': 'Network Authentication Required',\n 'description': '\"The client needs to authenticate to gain network access.\"',\n 'spec_title': 'RFC6585#6',\n 'spec_href': 'https://tools.ietf.org/html/rfc6585#section-6',\n },\n};\n\n/**\n * get the status text from StatusCode\n */\nexport function getStatusText(code: number) {\n return STATUS_CODE_INFO[code + ''].text || 'Unknown Status';\n}\n\n/**\n * Returns true if the Http Status Code is 200-299 (success)\n */\nexport function isSuccess(status: number): boolean {\n return status >= 200 && status < 300;\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {HttpHeaders} from '@angular/common/http';\nimport {Injectable} from '@angular/core';\nimport {Observable} from 'rxjs';\n\n/**\n * Interface for a class that creates an in-memory database\n *\n * Its `createDb` method creates a hash of named collections that represents the database\n *\n * For maximum flexibility, the service may define HTTP method overrides.\n * Such methods must match the spelling of an HTTP method in lower case (e.g, \"get\").\n * If a request has a matching method, it will be called as in\n * `get(info: requestInfo, db: {})` where `db` is the database object described above.\n */\nexport abstract class InMemoryDbService {\n /**\n * Creates an in-memory \"database\" hash whose keys are collection names\n * and whose values are arrays of collection objects to return or update.\n *\n * returns Observable of the database because could have to create it asynchronously.\n *\n * This method must be safe to call repeatedly.\n * Each time it should return a new object with new arrays containing new item objects.\n * This condition allows the in-memory backend service to mutate the collections\n * and their items without touching the original source data.\n *\n * The in-mem backend service calls this method without a value the first time.\n * The service calls it with the `RequestInfo` when it receives a POST `commands/resetDb` request.\n * Your InMemoryDbService can adjust its behavior accordingly.\n */\n abstract createDb(reqInfo?: RequestInfo): {} | Observable<{}> | Promise<{}>;\n}\n\n/**\n * Interface for InMemoryBackend configuration options\n */\nexport abstract class InMemoryBackendConfigArgs {\n /**\n * The base path to the api, e.g, 'api/'.\n * If not specified than `parseRequestUrl` assumes it is the first path segment in the request.\n */\n apiBase?: string;\n /**\n * false (default) if search match should be case insensitive\n */\n caseSensitiveSearch?: boolean;\n /**\n * false (default) put content directly inside the response body.\n * true: encapsulate content in a `data` property inside the response body, `{ data: ... }`.\n */\n dataEncapsulation?: boolean;\n /**\n * delay (in ms) to simulate latency\n */\n delay?: number;\n /**\n * false (default) should 204 when object-to-delete not found; true: 404\n */\n delete404?: boolean;\n /**\n * host for this service, e.g., 'localhost'\n */\n host?: string;\n /**\n * true, should pass unrecognized request URL through to original backend; false (default): 404\n */\n passThruUnknownUrl?: boolean;\n /**\n * true (default) should NOT return the item (204) after a POST. false: return the item (200).\n */\n post204?: boolean;\n /**\n * false (default) should NOT update existing item with POST. false: OK to update.\n */\n post409?: boolean;\n /**\n * true (default) should NOT return the item (204) after a POST. false: return the item (200).\n */\n put204?: boolean;\n /**\n * false (default) if item not found, create as new item; false: should 404.\n */\n put404?: boolean;\n /**\n * root path _before_ any API call, e.g., ''\n */\n rootPath?: string;\n}\n\n/////////////////////////////////\n/**\n * InMemoryBackendService configuration options\n * Usage:\n * InMemoryWebApiModule.forRoot(InMemHeroService, {delay: 600})\n *\n * or if providing separately:\n * provide(InMemoryBackendConfig, {useValue: {delay: 600}}),\n */\n@Injectable()\nexport class InMemoryBackendConfig implements InMemoryBackendConfigArgs {\n constructor(config: InMemoryBackendConfigArgs = {}) {\n Object.assign(\n this,\n {\n // default config:\n caseSensitiveSearch: false,\n dataEncapsulation: false, // do NOT wrap content within an object with a `data` property\n delay: 500, // simulate latency by delaying response\n delete404: false, // don't complain if can't find entity to delete\n passThruUnknownUrl: false, // 404 if can't process URL\n post204: true, // don't return the item after a POST\n post409: false, // don't update existing item with that ID\n put204: true, // don't return the item after a PUT\n put404: false, // create new item if PUT item with that ID not found\n apiBase: undefined, // assumed to be the first path segment\n host: undefined, // default value is actually set in InMemoryBackendService ctor\n rootPath: undefined, // default value is actually set in InMemoryBackendService ctor\n },\n config,\n );\n }\n}\n\n/** Return information (UriInfo) about a URI */\nexport function parseUri(str: string): UriInfo {\n // Adapted from parseuri package - http://blog.stevenlevithan.com/archives/parseuri\n const URL_REGEX =\n /^(?:(?![^:@]+:[^:@\\/]*@)([^:\\/?#.]+):)?(?:\\/\\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\\/?#]*)(?::(\\d*))?)(((\\/(?:[^?#](?![^?#\\/]*\\.[^?#\\/.]+(?:[?#]|$)))*\\/?)?([^?#\\/]*))(?:\\?([^#]*))?(?:#(.*))?)/;\n const m = URL_REGEX.exec(str);\n const uri: UriInfo & {[key: string]: string} = {\n source: '',\n protocol: '',\n authority: '',\n userInfo: '',\n user: '',\n password: '',\n host: '',\n port: '',\n relative: '',\n path: '',\n directory: '',\n file: '',\n query: '',\n anchor: '',\n };\n const keys = Object.keys(uri);\n let i = keys.length;\n\n while (i--) {\n uri[keys[i]] = (m && m[i]) || '';\n }\n return uri;\n}\n\n/**\n *\n * Interface for the result of the `parseRequestUrl` method:\n * Given URL \"http://localhost:8080/api/customers/42?foo=1 the default implementation returns\n * base: 'api/'\n * collectionName: 'customers'\n * id: '42'\n * query: this.createQuery('foo=1')\n * resourceUrl: 'http://localhost/api/customers/'\n */\nexport interface ParsedRequestUrl {\n apiBase: string; // the slash-terminated \"base\" for api requests (e.g. `api/`)\n collectionName: string; // the name of the collection of data items (e.g.,`customers`)\n id: string; // the (optional) id of the item in the collection (e.g., `42`)\n query: Map<string, string[]>; // the query parameters;\n resourceUrl: string; // the effective URL for the resource (e.g., 'http://localhost/api/customers/')\n}\n\nexport interface PassThruBackend {\n /**\n * Handle an HTTP request and return an Observable of HTTP response\n * Both the request type and the response type are determined by the supporting HTTP library.\n */\n handle(req: any): Observable<any>;\n}\n\nexport function removeTrailingSlash(path: string) {\n return path.replace(/\\/$/, '');\n}\n\n/**\n * Minimum definition needed by base class\n */\nexport interface RequestCore {\n url: string; // request URL\n urlWithParams?: string; // request URL with query parameters added by `HttpParams`\n}\n\n/**\n * Interface for object w/ info about the current request url\n * extracted from an Http Request.\n * Also holds utility methods and configuration data from this service\n */\nexport interface RequestInfo {\n req: RequestCore; // concrete type depends upon the Http library\n apiBase: string;\n collectionName: string;\n collection: any;\n headers: HttpHeaders;\n method: string;\n id: any;\n query: Map<string, string[]>;\n resourceUrl: string;\n url: string; // request URL\n utils: RequestInfoUtilities;\n}\n\n/**\n * Interface for utility methods from this service instance.\n * Useful within an HTTP method override\n */\nexport interface RequestInfoUtilities {\n /**\n * Create a cold response Observable from a factory for ResponseOptions\n * the same way that the in-mem backend service does.\n * @param resOptionsFactory - creates ResponseOptions when observable is subscribed\n * @param withDelay - if true (default), add simulated latency delay from configuration\n */\n createResponse$: (resOptionsFactory: () => ResponseOptions) => Observable<any>;\n\n /**\n * Find first instance of item in collection by `item.id`\n * @param collection\n * @param id\n */\n findById<T extends {id: any}>(collection: T[], id: any): T | undefined;\n\n /** return the current, active configuration which is a blend of defaults and overrides */\n getConfig(): InMemoryBackendConfigArgs;\n\n /** Get the in-mem service's copy of the \"database\" */\n getDb(): {};\n\n /** Get JSON body from the request object */\n getJsonBody(req: any): any;\n\n /** Get location info from a url, even on server where `document` is not defined */\n getLocation(url: string): UriInfo;\n\n /** Get (or create) the \"real\" backend */\n getPassThruBackend(): PassThruBackend;\n\n /**\n * return true if can determine that the collection's `item.id` is a number\n * */\n isCollectionIdNumeric<T extends {id: any}>(collection: T[], collectionName: string): boolean;\n\n /**\n * Parses the request URL into a `ParsedRequestUrl` object.\n * Parsing depends upon certain values of `config`: `apiBase`, `host`, and `urlRoot`.\n */\n parseRequestUrl(url: string): ParsedRequestUrl;\n}\n\n/**\n * Provide a `responseInterceptor` method of this type in your `inMemDbService` to\n * morph the response options created in the `collectionHandler`.\n */\nexport type ResponseInterceptor = (res: ResponseOptions, ri: RequestInfo) => ResponseOptions;\n\nexport interface ResponseOptions {\n /**\n * String, Object, ArrayBuffer or Blob representing the body of the {@link Response}.\n */\n body?: string | Object | ArrayBuffer | Blob;\n\n /**\n * Response headers\n */\n headers?: HttpHeaders;\n\n /**\n * Http {@link https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html status code}\n * associated with the response.\n */\n status?: number;\n\n /**\n * Status text for the status code\n */\n statusText?: string;\n /**\n * request url\n */\n url?: string;\n}\n\n/** Interface of information about a Uri */\nexport interface UriInfo {\n source: string;\n protocol: string;\n authority: string;\n userInfo: string;\n user: string;\n password: string;\n host: string;\n port: string;\n relative: string;\n path: string;\n directory: string;\n file: string;\n query: string;\n anchor: string;\n}\n","/**\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.dev/license\n */\n\nimport {HttpHeaders} from '@angular/common/http';\nimport {BehaviorSubject, from, Observable, Observer, of} from 'rxjs';\nimport {concatMap, first} from 'rxjs/operators';\n\nimport {delayResponse} from './delay-response';\nimport {getStatusText, isSuccess, STATUS} from './http-status-codes';\nimport {\n InMemoryBackendConfig,\n InMemoryBackendConfigArgs,\n InMemoryDbService,\n ParsedRequestUrl,\n parseUri,\n PassThruBackend,\n removeTrailingSlash,\n RequestCore,\n RequestInfo,\n RequestInfoUtilities,\n ResponseOptions,\n UriInfo,\n} from './interfaces';\n\n/**\n * Base class for in-memory web api back-ends\n * Simulate the behavior of a RESTy web api\n * backed by the simple in-memory data store provided by the injected `InMemoryDbService` service.\n * Conforms mostly to behavior described here:\n * http://www.restapitutorial.com/lessons/httpmethods.html\n */\nexport abstract class BackendService {\n protected config: InMemoryBackendConfigArgs = new InMemoryBackendConfig();\n protected db: {[key: string]: any} = {};\n protected dbReadySubject: BehaviorSubject<boolean> | undefined;\n private passThruBackend: PassThruBackend | undefined;\n protected requestInfoUtils = this.getRequestInfoUtils();\n\n constructor(\n protected inMemDbService: InMemoryDbService,\n config: InMemoryBackendConfigArgs = {},\n ) {\n const loc = this.getLocation('/');\n this.config.host = loc.host; // default to app web server host\n this.config.rootPath = loc.path; // default to path when app is served (e.g.'/')\n Object.assign(this.config, config);\n }\n\n protected get dbReady(): Observable<boolean> {\n if (!this.dbReadySubject) {\n // first time the service is called.\n this.dbReadySubject = new BehaviorSubject<boolean>(false);\n this.resetDb();\n }\n return this.dbReadySubject.asObservable().pipe(first((r: boolean) => r));\n }\n\n /**\n * Process Request and return an Observable of Http Response object\n * in the manner of a RESTy web api.\n *\n * Expect URI pattern in the form :base/:collectionName/:id?\n * Examples:\n * // for store with a 'customers' collection\n * GET api/customers // all customers\n * GET api/customers/42 // the character with id=42\n * GET api/customers?name=^j // 'j' is a regex; returns customers whose name starts with 'j' or\n * 'J' GET api/customers.json/42 // ignores the \".json\"\n *\n * Also accepts direct commands to the service in which the last segment of the apiBase is the\n * word \"commands\" Examples: POST commands/resetDb, GET/POST commands/config - get or (re)set the\n * config\n *\n * HTTP overrides:\n * If the injected inMemDbService defines an HTTP method (lowercase)\n * The request is forwarded to that method as in\n * `inMemDbService.get(requestInfo)`\n * which must return either an Observable of the response type\n * for this http library or null|undefined (which means \"keep processing\").\n */\n protected handleRequest(req: RequestCore): Observable<any> {\n // handle the request when there is an in-memory database\n return this.dbReady.pipe(concatMap(() => this.handleRequest_(req)));\n }\n\n protected handleRequest_(req: RequestCore): Observable<any> {\n const url = req.urlWithParams ? req.urlWithParams : req.url;\n\n // Try override parser\n // If no override parser or it returns nothing, use default parser\n const parser = this.bind('parseRequestUrl');\n const parsed: ParsedRequestUrl =\n (parser && parser(url, this.requestInfoUtils)) || this.parseRequestUrl(url);\n\n const collectionName = parsed.collectionName;\n const collection = this.db[collectionName];\n\n const reqInfo: RequestInfo = {\n req: req,\n apiBase: parsed.apiBase,\n collection: collection,\n collectionName: collectionName,\n headers: this.createHeaders({'Content-Type': 'application/json'}),\n id: this.parseId(collection, collectionName, parsed.id),\n method: this.getRequestMethod(req),\n query: parsed.query,\n resourceUrl: parsed.resourceUrl,\n url: url,\n utils: this.requestInfoUtils,\n };\n\n let resOptions: ResponseOptions;\n\n if (/commands\\/?$/i.test(reqInfo.apiBase)) {\n return this.commands(reqInfo);\n }\n\n const methodInterceptor = this.bind(reqInfo.method);\n if (methodInterceptor) {\n // InMemoryDbService intercepts this HTTP method.\n // if interceptor produced a response, return it.\n // else InMemoryDbService chose not to intercept; continue processing.\n const interceptorResponse = methodInterceptor(reqInfo);\n if (interceptorResponse) {\n return interceptorResponse;\n }\n }\n\n if (this.db[collectionName]) {\n // request is for a known collection of the InMemoryDbService\n return this.createResponse$(() => this.collectionHandler(reqInfo));\n }\n\n if (this.config.passThruUnknownUrl) {\n // unknown collection; pass request thru to a \"real\" backend.\n return this.getPassThruBackend().handle(req);\n }\n\n // 404 - can't handle this request\n resOptions = this.createErrorResponseOptions(\n url,\n STATUS.NOT_FOUND,\n `Collection '${collectionName}' not found`,\n );\n return this.createResponse$(() => resOptions);\n }\n\n /**\n * Add configured delay to response observable unless delay === 0\n */\n protected addDelay(response: Observable<any>): Observable<any> {\n const d = this.config.delay;\n return d === 0 ? response : delayResponse(response, d || 500);\n }\n\n /**\n * Apply query/search parameters as a filter over the collection\n * This impl only supports RegExp queries on string properties of the collection\n * ANDs the conditions together\n */\n protected applyQuery(collection: any[], query: Map<string, string[]>): any[] {\n // extract filtering conditions - {propertyName, RegExps) - from query/search parameters\n const conditions: {name: string; rx: RegExp}[] = [];\n const caseSensitive = this.config.caseSensitiveSearch ? undefined : 'i';\n query.forEach((value: string[], name: string) => {\n value.forEach((v) => conditions.push({name, rx: new RegExp(decodeURI(v), caseSensitive)}));\n });\n\n const len = conditions.length;\n if (!len) {\n return collection;\n }\n\n // AND the RegExp conditions\n return collection.filter((row) => {\n let ok = true;\n let i = len;\n while (ok && i) {\n i -= 1;\n const cond = conditions[i];\n ok = cond.rx.test(row[cond.name]);\n }\n return ok;\n });\n }\n\n /**\n * Get a method from the `InMemoryDbService` (if it exists), bound to that service\n */\n protected bind<T extends Function>(methodName: string) {\n const fn = (this.inMemDbService as any)[methodName];\n return fn ? (fn.bind(this.inMemDbService) as T) : undefined;\n }\n\n protected bodify(data: any) {\n return this.config.dataEncapsulation ? {data} : data;\n }\n\n protected clone(data: any) {\n return JSON.parse(JSON.stringify(data));\n }\n\n protected collectionHandler(reqInfo: RequestInfo): ResponseOptions {\n // const req = reqInfo.req;\n let resOptions: ResponseOptions;\n switch (reqInfo.method) {\n case 'get':\n resOptions = this.get(reqInfo);\n break;\n case 'post':\n resOptions = this.post(reqInfo);\n break;\n case 'put':\n resOptions = this.put(reqInfo);\n break;\n case 'delete':\n resOptions = this.delete(reqInfo);\n break;\n default:\n resOptions = this.createErrorResponseOptions(\n reqInfo.url,\n STATUS.METHOD_NOT_ALLOWED,\n 'Method not allowed',\n );\n break;\n }\n\n // If `inMemDbService.responseInterceptor` exists, let it morph the response options\n const interceptor = this.bind('responseInterceptor');\n return interceptor ? interceptor(resOptions, reqInfo) : resOptions;\n }\n\n /**\n * Commands reconfigure the in-memory web api service or extract information from it.\n * Commands ignore the latency delay and respond ASAP.\n *\n * When the last segment of the `apiBase` path is \"commands\",\n * the `collectionName` is the command.\n *\n * Example URLs:\n * commands/resetdb (POST) // Reset the \"database\" to its original state\n * commands/config (GET) // Return this service's config object\n * commands/config (POST) // Update the config (e.g. the delay)\n *\n * Usage:\n * http.post('commands/resetdb', undefined);\n * http.get('commands/config');\n * http.post('commands/config', '{\"delay\":1000}');\n */\n protected commands(reqInfo: RequestInfo): Observable<any> {\n const command = reqInfo.collectionName.toLowerCase();\n const method = reqInfo.method;\n\n let resOptions: ResponseOptions = {url: reqInfo.url};\n\n switch (command) {\n case 'resetdb':\n resOptions.status = STATUS.NO_CONTENT;\n return this.resetDb(reqInfo).pipe(\n concatMap(() => this.createResponse$(() => resOptions, false /* no latency delay */)),\n );\n\n case 'config':\n if (method === 'get') {\n resOptions.status = STATUS.OK;\n resOptions.body = this.clone(this.config);\n\n // any other HTTP method is assumed to be a config update\n } else {\n const body = this.getJsonBody(reqInfo.req);\n Object.assign(this.config, body);\n this.passThruBackend = undefined; // re-create when needed\n\n resOptions.status = STATUS.NO_CONTENT;\n }\n break;\n\n default:\n resOptions = this.createErrorResponseOptions(\n reqInfo.url,\n STATUS.INTERNAL_SERVER_ERROR,\n `Unknown command \"${command}\"`,\n );\n }\n\n return this.createResponse$(() => resOptions, false /* no latency delay */);\n }\n\n protected createErrorResponseOptions(\n url: string,\n status: number,\n message: string,\n ): ResponseOptions {\n return {\n body: {error: `${message}`},\n url: url,\n headers: this.createHeaders({'Content-Type': 'application/json'}),\n status: status,\n };\n }\n\n /**\n * Create standard HTTP headers object from hash map of header strings\n * @param headers\n */\n protected abstract createHeaders(headers: {[index: string]: string}): HttpHeaders;\n\n /**\n * create the function that passes unhandled requests through to the \"real\" backend.\n */\n protected abstract createPassThruBackend(): PassThruBackend;\n\n /**\n * return a search map from a location query/search string\n */\n protected abstract createQueryMap(search: string): Map<string, string[]>;\n\n /**\n * Create a cold response Observable from a factory for ResponseOptions\n * @param resOptionsFactory - creates ResponseOptions when observable is subscribed\n * @param withDelay - if true (default), add simulated latency delay from configuration\n */\n protected createResponse$(\n resOptionsFactory: () => ResponseOptions,\n withDelay = true,\n ): Observable<any> {\n const resOptions$ = this.createResponseOptions$(resOptionsFactory);\n let resp$ = this.createResponse$fromResponseOptions$(resOptions$);\n return withDelay ? this.addDelay(resp$) : resp$;\n }\n\n /**\n * Create a Response observable from ResponseOptions observable.\n */\n protected abstract createResponse$fromResponseOptions$(\n resOptions$: Observable<ResponseOptions>,\n ): Observable<any>;\n\n /**\n * Create a cold Observable of ResponseOptions.\n * @param resOptionsFactory - creates ResponseOptions when observable is subscribed\n */\n protected createResponseOptions$(\n resOptionsFactory: () => ResponseOptions,\n ): Observable<ResponseOptions> {\n return new Observable<ResponseOptions>((responseObserver: Observer<ResponseOptions>) => {\n let resOptions: ResponseOptions;\n try {\n resOptions = resOptionsFactory();\n } catch (error) {\n const err = (error as Error).message || error;\n resOptions = this.createErrorResponseOptions('', STATUS.INTERNAL_SERVER_ERROR, `${err}`);\n }\n\n const status = resOptions.status;\n try {\n resOptions.statusText = status != null ? getStatusText(status) : undefined;\n } catch (e) {\n /* ignore failure */\n }\n if (status != null && isSuccess(status)) {\n responseObserver.next(resOptions);\n responseObserver.complete();\n } else {\n responseObserver.error(resOptions);\n }\n return () => {}; // unsubscribe function\n });\n }\n\n protected delete({collection, collectionName, headers, id, url}: RequestInfo): ResponseOptions {\n if (id == null) {\n return this.createErrorResponseOptions(\n url,\n STATUS.NOT_FOUND,\n `Missing \"${collectionName}\" id`,\n );\n }\n const exists = this.removeById(collection, id);\n return {\n headers: headers,\n status: exists || !this.config.delete404 ? STATUS.NO_CONTENT : STATUS.NOT_FOUND,\n };\n }\n\n /**\n * Find first instance of item in collection by `item.id`\n * @param collection\n * @param id\n */\n protected findById<T extends {id: any}>(collection: T[], id: any): T | undefined {\n return collection.find((item: T) => item.id === id);\n }\n\n /**\n * Generate the next available id for item in this collection\n * Use method from `inMemDbService` if it exists and returns a value,\n * else delegates to `genIdDefault`.\n * @param collection - collection of items with `id` key property\n */\n protected genId<T extends {id: any}>(collection: T[], collectionName: string): any {\n const genId = this.bind('genId');\n if (genId) {\n const id = genId(collection, collectionName);\n if (id != null) {\n return id;\n }\n }\n return this.genIdDefault(collection, collectionName);\n }\n\n /**\n * Default generator of the next available id for item in this collection\n * This default implementation works only for numeric ids.\n * @param collection - collection of items with `id` key property\n * @param collectionName - name of the collection\n */\n protected genIdDefault<T extends {id: any}>(collection: T[], collectionName: string): any {\n if (!this.isCollectionIdNumeric(collection, collectionName)) {\n throw new Error(\n `Collection '${collectionName}' id type is non-numeric or unknown. Can only generate numeric ids.`,\n );\n }\n\n let maxId = 0;\n collection.reduce((prev: any, item: any) => {\n maxId = Math.max(maxId, typeof item.id === 'number' ? item.id : maxId);\n }, undefined);\n return maxId + 1;\n }\n\n protected get({\n collection,\n collectionName,\n headers,\n id,\n query,\n url,\n }: RequestInfo): ResponseOptions {\n let data = collection;\n\n if (id != null && id !== '') {\n data = this.findById(collection, id);\n } else if (query) {\n data = this.applyQuery(collection, query);\n }\n\n if (!data) {\n return this.createErrorResponseOptions(\n url,\n STATUS.NOT_FOUND,\n `'${collectionName}' with id='${id}' not found`,\n );\n }\n return {body: this.bodify(this.clone(data)), headers: headers, status: STATUS.OK};\n }\n\n /** Get JSON body from the request object */\n protected abstract getJsonBody(req: any): any;\n\n /**\n * Get location info from a url, even on server where `document` is not defined\n */\n protected getLocation(url: string): UriInfo {\n if (!url.startsWith('http')) {\n // get the document iff running in browser\n const doc = typeof document === 'undefined' ? undefined : document;\n // add host info to url before parsing. Use a fake host when not in browser.\n const base = doc ? doc.location.protocol + '//' + doc.location.host : 'http://fake';\n url = url.startsWith('/') ? base + url : base + '/' + url;\n }\n return parseUri(url);\n }\n\n /**\n * get or create the function th