@zuplo/cli 7.1.8 → 7.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/node_modules/@hono/node-server/dist/index.cjs +151 -9
- package/node_modules/@hono/node-server/dist/index.mjs +151 -9
- package/node_modules/@hono/node-server/package.json +1 -1
- package/node_modules/@posthog/core/dist/posthog-core-stateless.d.ts +24 -3
- package/node_modules/@posthog/core/dist/posthog-core-stateless.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/posthog-core-stateless.js +30 -9
- package/node_modules/@posthog/core/dist/posthog-core-stateless.mjs +28 -10
- package/node_modules/@posthog/core/dist/posthog-core.d.ts +3 -3
- package/node_modules/@posthog/core/dist/posthog-core.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/posthog-core.js +1 -0
- package/node_modules/@posthog/core/dist/posthog-core.mjs +1 -0
- package/node_modules/@posthog/core/dist/surveys/translations.d.ts +3 -5
- package/node_modules/@posthog/core/dist/surveys/translations.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/surveys/translations.js +19 -21
- package/node_modules/@posthog/core/dist/surveys/translations.mjs +19 -21
- package/node_modules/@posthog/core/dist/types.d.ts +10 -1
- package/node_modules/@posthog/core/dist/types.d.ts.map +1 -1
- package/node_modules/@posthog/core/dist/types.js +1 -0
- package/node_modules/@posthog/core/dist/types.mjs +1 -0
- package/node_modules/@posthog/core/package.json +2 -2
- package/node_modules/@posthog/core/src/posthog-core-stateless.ts +42 -10
- package/node_modules/@posthog/core/src/posthog-core.ts +4 -3
- package/node_modules/@posthog/core/src/surveys/translations.spec.ts +26 -0
- package/node_modules/@posthog/core/src/surveys/translations.ts +23 -33
- package/node_modules/@posthog/core/src/types.ts +13 -1
- package/node_modules/@posthog/types/dist/capture.d.ts +1 -1
- package/node_modules/@posthog/types/dist/index.d.ts +1 -1
- package/node_modules/@posthog/types/dist/index.d.ts.map +1 -1
- package/node_modules/@posthog/types/dist/posthog-config.d.ts +54 -5
- package/node_modules/@posthog/types/dist/posthog-config.d.ts.map +1 -1
- package/node_modules/@posthog/types/dist/posthog.d.ts +3 -3
- package/node_modules/@posthog/types/dist/posthog.d.ts.map +1 -1
- package/node_modules/@posthog/types/dist/segment.d.ts +11 -2
- package/node_modules/@posthog/types/dist/segment.d.ts.map +1 -1
- package/node_modules/@posthog/types/package.json +1 -1
- package/node_modules/@posthog/types/src/capture.ts +1 -1
- package/node_modules/@posthog/types/src/index.ts +1 -0
- package/node_modules/@posthog/types/src/posthog-config.ts +64 -6
- package/node_modules/@posthog/types/src/posthog.ts +3 -3
- package/node_modules/@posthog/types/src/segment.ts +11 -2
- package/node_modules/@zuplo/core/package.json +1 -1
- package/node_modules/@zuplo/graphql/package.json +1 -1
- package/node_modules/@zuplo/openapi-tools/package.json +1 -1
- package/node_modules/@zuplo/otel/package.json +1 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-4VE55TG3.js +26 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-4VE55TG3.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-DEKK4CFE.js +382 -0
- package/node_modules/@zuplo/runtime/out/esm/chunk-DEKK4CFE.js.map +1 -0
- package/node_modules/@zuplo/runtime/out/esm/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/esm/mcp-gateway/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/esm/mocks/index.js +1 -1
- package/node_modules/@zuplo/runtime/out/types/index.d.ts +20 -8
- package/node_modules/@zuplo/runtime/out/types/internal/index.d.ts +1 -0
- package/node_modules/@zuplo/runtime/out/types/mcp/messages/index.d.ts +1 -0
- package/node_modules/@zuplo/runtime/out/types/mcp-gateway/index.d.ts +1 -0
- package/node_modules/@zuplo/runtime/out/types/mocks/index.d.ts +1 -0
- package/node_modules/@zuplo/runtime/out/types/sdks/aws/index.d.ts +1 -0
- package/node_modules/@zuplo/runtime/package.json +1 -1
- package/node_modules/ansi-regex/index.js +3 -2
- package/node_modules/ansi-regex/package.json +1 -1
- package/node_modules/body-parser/node_modules/content-type/README.md +2 -0
- package/node_modules/body-parser/node_modules/content-type/dist/index.d.ts +20 -0
- package/node_modules/body-parser/node_modules/content-type/dist/index.js +20 -14
- package/node_modules/body-parser/node_modules/content-type/dist/index.js.map +1 -1
- package/node_modules/body-parser/node_modules/content-type/package.json +1 -1
- package/node_modules/eventsource-parser/dist/index.cjs +2 -2
- package/node_modules/eventsource-parser/dist/index.cjs.map +1 -1
- package/node_modules/eventsource-parser/dist/index.js +2 -2
- package/node_modules/eventsource-parser/dist/index.js.map +1 -1
- package/node_modules/eventsource-parser/package.json +1 -1
- package/node_modules/eventsource-parser/src/parse.ts +4 -2
- package/node_modules/hono/dist/cjs/client/client.js +3 -3
- package/node_modules/hono/dist/cjs/jsx/intrinsic-element/components.js +1 -1
- package/node_modules/hono/dist/cjs/middleware/cors/index.js +15 -12
- package/node_modules/hono/dist/cjs/middleware/etag/digest.js +47 -1
- package/node_modules/hono/dist/cjs/middleware/secure-headers/secure-headers.js +6 -3
- package/node_modules/hono/dist/cjs/utils/url.js +2 -2
- package/node_modules/hono/dist/client/client.js +3 -3
- package/node_modules/hono/dist/jsx/intrinsic-element/components.js +1 -1
- package/node_modules/hono/dist/middleware/cors/index.js +15 -12
- package/node_modules/hono/dist/middleware/etag/digest.js +47 -1
- package/node_modules/hono/dist/middleware/secure-headers/secure-headers.js +6 -3
- package/node_modules/hono/dist/types/middleware/secure-headers/permissions-policy.d.ts +3 -3
- package/node_modules/hono/dist/utils/url.js +2 -2
- package/node_modules/hono/package.json +1 -1
- package/node_modules/ip-address/README.md +134 -134
- package/node_modules/ip-address/dist/address-error.d.ts +11 -0
- package/node_modules/ip-address/dist/address-error.js.map +1 -1
- package/node_modules/ip-address/dist/ipv4.d.ts +22 -6
- package/node_modules/ip-address/dist/ipv4.js +22 -6
- package/node_modules/ip-address/dist/ipv4.js.map +1 -1
- package/node_modules/ip-address/dist/ipv6.d.ts +10 -3
- package/node_modules/ip-address/dist/ipv6.js +26 -17
- package/node_modules/ip-address/dist/ipv6.js.map +1 -1
- package/node_modules/ip-address/package.json +1 -1
- package/node_modules/type-is/node_modules/content-type/README.md +2 -0
- package/node_modules/type-is/node_modules/content-type/dist/index.d.ts +20 -0
- package/node_modules/type-is/node_modules/content-type/dist/index.js +20 -14
- package/node_modules/type-is/node_modules/content-type/dist/index.js.map +1 -1
- package/node_modules/type-is/node_modules/content-type/package.json +1 -1
- package/package.json +6 -6
- package/node_modules/@zuplo/runtime/out/esm/chunk-RAZK5G27.js +0 -26
- package/node_modules/@zuplo/runtime/out/esm/chunk-RAZK5G27.js.map +0 -1
- package/node_modules/@zuplo/runtime/out/esm/chunk-Y57PFQJ3.js +0 -382
- package/node_modules/@zuplo/runtime/out/esm/chunk-Y57PFQJ3.js.map +0 -1
- /package/node_modules/@zuplo/runtime/out/esm/{chunk-Y57PFQJ3.js.LEGAL.txt → chunk-DEKK4CFE.js.LEGAL.txt} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/errors.ts","../src/parse.ts"],"sourcesContent":["/**\n * The type of error that occurred.\n * @public\n */\nexport type ErrorType = 'invalid-retry' | 'unknown-field' | 'max-buffer-size-exceeded'\n\n/**\n * Error thrown when encountering an issue during parsing.\n *\n * @public\n */\nexport class ParseError extends Error {\n /**\n * The type of error that occurred.\n */\n type: ErrorType\n\n /**\n * In the case of an unknown field encountered in the stream, this will be the field name.\n */\n field?: string | undefined\n\n /**\n * In the case of an unknown field encountered in the stream, this will be the value of the field.\n */\n value?: string | undefined\n\n /**\n * The line that caused the error, if available.\n */\n line?: string | undefined\n\n constructor(\n message: string,\n options: {type: ErrorType; field?: string; value?: string; line?: string},\n ) {\n super(message)\n this.name = 'ParseError'\n this.type = options.type\n this.field = options.field\n this.value = options.value\n this.line = options.line\n }\n}\n","/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nimport {ParseError} from './errors.ts'\nimport type {EventSourceParser, ParserConfig} from './types.ts'\n\n// ASCII codes used in the hot parsing paths.\nconst LF = 10\nconst CR = 13\nconst SPACE = 32\n\n// oxlint-disable-next-line no-unused-vars\nfunction noop(_arg: unknown) {\n // intentional noop\n}\n\n/**\n * Creates a new EventSource parser.\n *\n * @param config - Parser configuration. Accepts callbacks (see {@link ParserCallbacks})\n * and options like `maxBufferSize` (see {@link ParserConfig}).\n *\n * @returns A new EventSource parser, with `feed` and `reset` methods.\n * @public\n */\nexport function createParser(config: ParserConfig): EventSourceParser {\n if (typeof config === 'function') {\n throw new TypeError(\n '`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?',\n )\n }\n\n const {onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize} = config\n\n // Trailing bytes from prior `feed()` calls that did not yet form a complete line.\n // Stored as an array of fragments and only joined when a line terminator arrives.\n // Concatenating per-feed (`prefix + chunk`) is O(N²) when a single SSE line spans\n // many chunks (e.g. a large `data:` payload streamed in tiny slices, or an MCP-style\n // server that emits one giant content block). Buffering as fragments + joining once\n // makes the same workload linear.\n const pendingFragments: string[] = []\n\n // Running total of `pendingFragments` lengths, kept in sync with the array so the\n // `maxBufferSize` check doesn't have to walk the fragment list on every feed.\n let pendingFragmentsLength = 0\n\n let isFirstChunk = true\n let id: string | undefined\n let data = ''\n let dataLines = 0\n let eventType: string | undefined\n\n // Set after a `maxBufferSize` overflow. Once tripped, `feed()` throws until\n // `reset()` is called — see the comment on `maxBufferSize` in `ParserConfig`.\n let terminated = false\n\n /**\n * Feeds a chunk of the SSE stream to the parser. Any trailing bytes that do\n * not yet form a complete line are held back and prepended to the next chunk,\n * so callers can pass arbitrary slices of the stream without worrying about\n * line boundaries.\n *\n * Per the SSE spec, a UTF-8 BOM (0xEF 0xBB 0xBF) at the start of the very\n * first chunk is stripped before parsing.\n *\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream\n */\n function feed(chunk: string) {\n if (terminated) {\n throw new Error(\n 'Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.',\n )\n }\n\n if (isFirstChunk) {\n isFirstChunk = false\n // Match and strip UTF-8 BOM from the start of the stream, if present.\n // (Per the spec, this is only valid at the very start of the stream)\n if (\n chunk.charCodeAt(0) === 0xef &&\n chunk.charCodeAt(1) === 0xbb &&\n chunk.charCodeAt(2) === 0xbf\n ) {\n chunk = chunk.slice(3)\n }\n }\n\n // Hot path: no buffered prefix from a prior partial line. Hand the chunk\n // straight to `processLines`, exactly like the original implementation.\n // Zero new work in the common case (every chunk ends with `\\n\\n`).\n if (pendingFragments.length === 0) {\n const trailing = processLines(chunk)\n if (trailing !== '') {\n pendingFragments.push(trailing)\n pendingFragmentsLength = trailing.length\n }\n checkBufferSize()\n return\n }\n\n // We have a buffered prefix. If this chunk also has no terminator, append\n // to the buffer without concatenating — that's the O(N²) trap we're\n // avoiding (large single `data:` payload split across many tiny chunks).\n if (chunk.indexOf('\\n') === -1 && chunk.indexOf('\\r') === -1) {\n pendingFragments.push(chunk)\n pendingFragmentsLength += chunk.length\n checkBufferSize()\n return\n }\n\n // Terminator arrived. Join the accumulated fragments + this chunk once,\n // process, and buffer any new trailing partial line.\n pendingFragments.push(chunk)\n const input = pendingFragments.join('')\n pendingFragments.length = 0\n pendingFragmentsLength = 0\n const trailing = processLines(input)\n if (trailing !== '') {\n pendingFragments.push(trailing)\n pendingFragmentsLength = trailing.length\n }\n checkBufferSize()\n }\n\n function checkBufferSize() {\n if (maxBufferSize === undefined) return\n if (pendingFragmentsLength + data.length <= maxBufferSize) return\n\n terminated = true\n pendingFragments.length = 0\n pendingFragmentsLength = 0\n id = undefined\n data = ''\n dataLines = 0\n eventType = undefined\n onError(\n new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {\n type: 'max-buffer-size-exceeded',\n }),\n )\n }\n\n /**\n * Splits `chunk` into SSE lines and dispatches each to the appropriate handler.\n * Returns any trailing bytes that did not terminate with a line break, so the\n * caller can prepend them to the next chunk.\n *\n * The SSE spec permits three line terminators: `\\n`, `\\r`, and `\\r\\n`. Real-world\n * streams almost always use plain `\\n`, so we take a fast path when no `\\r` is\n * present in the chunk. The slow path is spec-correct but does more work per line.\n */\n function processLines(chunk: string): string {\n let searchIndex = 0\n\n // Fast path: LF-only chunk (the common case for typical SSE servers).\n // We can scan forward with a single `indexOf('\\n')` per line and inline\n // the hot-path branches for `data:` and `event:` without the CR bookkeeping\n // the slow path needs.\n if (chunk.indexOf('\\r') === -1) {\n let lfIndex = chunk.indexOf('\\n', searchIndex)\n while (lfIndex !== -1) {\n // Blank line: end-of-event marker. Dispatch the accumulated event (if any)\n // and reset the buffered fields. This is hoisted out of `parseLine` because\n // it's the single most common line shape after `data:` lines.\n if (searchIndex === lfIndex) {\n if (dataLines > 0) {\n onEvent({id, event: eventType, data})\n }\n id = undefined\n data = ''\n dataLines = 0\n eventType = undefined\n searchIndex = lfIndex + 1\n lfIndex = chunk.indexOf('\\n', searchIndex)\n continue\n }\n const firstCharCode = chunk.charCodeAt(searchIndex)\n if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n // `data:` line — append the value to the event's data buffer.\n // 'data:'.length === 5, 'data: '.length === 6\n const valueStart =\n chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5\n const value = chunk.slice(valueStart, lfIndex)\n // Fast path within a fast path: if this is the first data line AND the\n // next char is another LF (i.e. `data:foo\\n\\n`), dispatch immediately\n // without ever writing to the `data` buffer. This is the shape of a\n // typical single-line SSE event (ChatGPT-style streams, etc.) and is\n // hot enough to be worth the duplication.\n if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n onEvent({id, event: eventType, data: value})\n id = undefined\n data = ''\n eventType = undefined\n searchIndex = lfIndex + 2\n lfIndex = chunk.indexOf('\\n', searchIndex)\n continue\n }\n // Multi-line data: concatenate with newline separator per spec.\n data = dataLines === 0 ? value : `${data}\\n${value}`\n dataLines++\n } else if (isEventPrefix(chunk, searchIndex, firstCharCode)) {\n // `event:` line — set the event type for the next dispatch. Per spec,\n // an empty value resets `event type` to its default (undefined here).\n // 'event:'.length === 6, 'event: '.length === 7\n eventType =\n chunk.slice(\n chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,\n lfIndex,\n ) || undefined\n } else {\n // Everything else: `id:`, `retry:`, comment lines (`:` prefix), unknown\n // fields, or malformed lines. These are rarer and go through the full\n // per-line parser, which handles the SSE field grammar in detail.\n parseLine(chunk, searchIndex, lfIndex)\n }\n searchIndex = lfIndex + 1\n lfIndex = chunk.indexOf('\\n', searchIndex)\n }\n return chunk.slice(searchIndex)\n }\n\n // Slow path: the chunk contains at least one `\\r`, so lines may be terminated\n // by `\\r`, `\\n`, or `\\r\\n`. We locate the next terminator by looking at both\n // the nearest `\\r` and `\\n` and picking whichever comes first.\n while (searchIndex < chunk.length) {\n const crIndex = chunk.indexOf('\\r', searchIndex)\n const lfIndex = chunk.indexOf('\\n', searchIndex)\n\n let lineEnd = -1\n if (crIndex !== -1 && lfIndex !== -1) {\n lineEnd = crIndex < lfIndex ? crIndex : lfIndex\n } else if (crIndex !== -1) {\n // A trailing `\\r` at the very end of the chunk is ambiguous: it could be\n // a bare-CR terminator, or the first half of a `\\r\\n` whose `\\n` arrives\n // in the next chunk. Defer until we see more input.\n if (crIndex === chunk.length - 1) {\n lineEnd = -1\n } else {\n lineEnd = crIndex\n }\n } else if (lfIndex !== -1) {\n lineEnd = lfIndex\n }\n\n if (lineEnd === -1) {\n break\n }\n\n parseLine(chunk, searchIndex, lineEnd)\n searchIndex = lineEnd + 1\n // If we just consumed a `\\r` and the next char is `\\n`, skip it so the\n // pair is treated as a single terminator rather than an empty line.\n if (chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF) {\n searchIndex++\n }\n }\n\n return chunk.slice(searchIndex)\n }\n\n function parseLine(chunk: string, start: number, end: number) {\n if (start === end) {\n dispatchEvent()\n return\n }\n\n const firstCharCode = chunk.charCodeAt(start)\n\n if (isDataPrefix(chunk, start, firstCharCode)) {\n // 'data:'.length === 5, 'data: '.length === 6\n const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5\n const value = chunk.slice(valueStart, end)\n data = dataLines === 0 ? value : `${data}\\n${value}`\n dataLines++\n return\n }\n\n if (isEventPrefix(chunk, start, firstCharCode)) {\n // 'event:'.length === 6, 'event: '.length === 7\n eventType =\n chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined\n return\n }\n\n // Fast path for \"id:\" — 'i' = 105, 'd' = 100, ':' = 58\n if (\n firstCharCode === 105 &&\n chunk.charCodeAt(start + 1) === 100 &&\n chunk.charCodeAt(start + 2) === 58\n ) {\n // 'id:'.length === 3, 'id: '.length === 4\n const value = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end)\n id = value.includes('\\0') ? undefined : value\n return\n }\n\n // Comment line — ':' = 58\n if (firstCharCode === 58) {\n if (onComment) {\n const line = chunk.slice(start, end)\n // skip ':' (+1), or ': ' (+2) when a space follows\n onComment(line.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1))\n }\n return\n }\n\n const line = chunk.slice(start, end)\n const fieldSeparatorIndex = line.indexOf(':')\n if (fieldSeparatorIndex === -1) {\n processField(line, '', line)\n return\n }\n\n const field = line.slice(0, fieldSeparatorIndex)\n // skip ':' (+1), or ': ' (+2) when a space follows\n const offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1\n const value = line.slice(fieldSeparatorIndex + offset)\n processField(field, value, line)\n }\n\n function processField(field: string, value: string, line: string) {\n // Field names must be compared literally, with no case folding performed.\n switch (field) {\n case 'event':\n // Set the `event type` buffer to field value\n eventType = value || undefined\n break\n case 'data':\n data = dataLines === 0 ? value : `${data}\\n${value}`\n dataLines++\n break\n case 'id':\n // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n // the field value. Otherwise, ignore the field.\n id = value.includes('\\0') ? undefined : value\n break\n case 'retry':\n // If the field value consists of only ASCII digits, then interpret the field value as an\n // integer in base ten, and set the event stream's reconnection time to that integer.\n // Otherwise, ignore the field.\n if (/^\\d+$/.test(value)) {\n onRetry(parseInt(value, 10))\n } else {\n onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: 'invalid-retry',\n value,\n line,\n }),\n )\n }\n break\n default:\n // Otherwise, the field is ignored.\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}…` : field}\"`,\n {type: 'unknown-field', field, value, line},\n ),\n )\n break\n }\n }\n\n function dispatchEvent() {\n if (dataLines > 0) {\n onEvent({\n id,\n event: eventType,\n data,\n })\n }\n\n id = undefined\n data = ''\n dataLines = 0\n eventType = undefined\n }\n\n function reset(options: {consume?: boolean} = {}) {\n if (options.consume && pendingFragments.length > 0) {\n const incompleteLine = pendingFragments.join('')\n parseLine(incompleteLine, 0, incompleteLine.length)\n }\n\n isFirstChunk = true\n id = undefined\n data = ''\n dataLines = 0\n eventType = undefined\n pendingFragments.length = 0\n pendingFragmentsLength = 0\n terminated = false\n }\n\n return {feed, reset}\n}\n\n/**\n * Checks if `chunk` starts with the literal `data:` at index `i`.\n *\n * Equivalent to `chunk.startsWith('data:', i)`, but benchmarks show this\n * hand-unrolled char-code comparison is ~20% faster on common event types.\n * The caller passes `firstCharCode` (the code at `i`) so it can be reused\n * across prefix checks.\n *\n * ASCII: 'd' = 100, 'a' = 97, 't' = 116, 'a' = 97, ':' = 58\n */\nfunction isDataPrefix(chunk: string, i: number, firstCharCode: number): boolean {\n return (\n firstCharCode === 100 &&\n chunk.charCodeAt(i + 1) === 97 &&\n chunk.charCodeAt(i + 2) === 116 &&\n chunk.charCodeAt(i + 3) === 97 &&\n chunk.charCodeAt(i + 4) === 58\n )\n}\n\n/**\n * Checks if `chunk` starts with the literal `event:` at index `i`.\n *\n * See {@link isDataPrefix} for why this is hand-unrolled rather than using\n * `String.prototype.startsWith`.\n *\n * ASCII: 'e' = 101, 'v' = 118, 'e' = 101, 'n' = 110, 't' = 116, ':' = 58\n */\nfunction isEventPrefix(chunk: string, i: number, firstCharCode: number): boolean {\n return (\n firstCharCode === 101 &&\n chunk.charCodeAt(i + 1) === 118 &&\n chunk.charCodeAt(i + 2) === 101 &&\n chunk.charCodeAt(i + 3) === 110 &&\n chunk.charCodeAt(i + 4) === 116 &&\n chunk.charCodeAt(i + 5) === 58\n )\n}\n"],"names":["trailing","value","line"],"mappings":"AAWO,MAAM,mBAAmB,MAAM;AAAA,EAqBpC,YACE,SACA,SACA;AACA,UAAM,OAAO,GACb,KAAK,OAAO,cACZ,KAAK,OAAO,QAAQ,MACpB,KAAK,QAAQ,QAAQ,OACrB,KAAK,QAAQ,QAAQ,OACrB,KAAK,OAAO,QAAQ;AAAA,EACtB;AACF;ACnCA,MAAM,KAAK,IACL,KAAK,IACL,QAAQ;AAGd,SAAS,KAAK,MAAe;AAE7B;AAWO,SAAS,aAAa,QAAyC;AACpE,MAAI,OAAO,UAAW;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAIJ,QAAM,EAAC,UAAU,MAAM,UAAU,MAAM,UAAU,MAAM,WAAW,cAAA,IAAiB,QAQ7E,mBAA6B,CAAA;AAInC,MAAI,yBAAyB,GAEzB,eAAe,IACf,IACA,OAAO,IACP,YAAY,GACZ,WAIA,aAAa;AAajB,WAAS,KAAK,OAAe;AAC3B,QAAI;AACF,YAAM,IAAI;AAAA,QACR;AAAA,MAAA;AAoBJ,QAhBI,iBACF,eAAe,IAIb,MAAM,WAAW,CAAC,MAAM,OACxB,MAAM,WAAW,CAAC,MAAM,OACxB,MAAM,WAAW,CAAC,MAAM,QAExB,QAAQ,MAAM,MAAM,CAAC,KAOrB,iBAAiB,WAAW,GAAG;AACjC,YAAMA,YAAW,aAAa,KAAK;AAC/BA,oBAAa,OACf,iBAAiB,KAAKA,SAAQ,GAC9B,yBAAy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AI,CAAC,MAAM,MAC5B,MAAM,WAAW,IAAI,CAAC,MAAM,OAC5B,MAAM,WAAW,IAAI,CAAC,MAAM,MAC5B,MAAM,WAAW,IAAI,CAAC,MAAM;AAEhC;AAUA,SAAS,cAAc,OAAe,GAAW,eAAgC;AAC/E,SACE,kBAAkB,OAClB,MAAM,WAAW,IAAI,CAAC,MAAM,OAC5B,MAAM,WAAW,IAAI,CAAC,MAAM,OAC5B,MAAM,WAAW,IAAI,CAAC,MAAM,OAC5B,MAAM,WAAW,IAAI,CAAC,MAAM,OAC5B,MAAM,WAAW,IAAI,CAAC,MAAM;AAEhC;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/errors.ts","../src/parse.ts"],"sourcesContent":["/**\n * The type of error that occurred.\n * @public\n */\nexport type ErrorType = 'invalid-retry' | 'unknown-field' | 'max-buffer-size-exceeded'\n\n/**\n * Error thrown when encountering an issue during parsing.\n *\n * @public\n */\nexport class ParseError extends Error {\n /**\n * The type of error that occurred.\n */\n type: ErrorType\n\n /**\n * In the case of an unknown field encountered in the stream, this will be the field name.\n */\n field?: string | undefined\n\n /**\n * In the case of an unknown field encountered in the stream, this will be the value of the field.\n */\n value?: string | undefined\n\n /**\n * The line that caused the error, if available.\n */\n line?: string | undefined\n\n constructor(\n message: string,\n options: {type: ErrorType; field?: string; value?: string; line?: string},\n ) {\n super(message)\n this.name = 'ParseError'\n this.type = options.type\n this.field = options.field\n this.value = options.value\n this.line = options.line\n }\n}\n","/**\n * EventSource/Server-Sent Events parser\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html\n */\nimport {ParseError} from './errors.ts'\nimport type {EventSourceParser, ParserConfig} from './types.ts'\n\n// ASCII codes used in the hot parsing paths.\nconst LF = 10\nconst CR = 13\nconst SPACE = 32\n\n// oxlint-disable-next-line no-unused-vars\nfunction noop(_arg: unknown) {\n // intentional noop\n}\n\n/**\n * Creates a new EventSource parser.\n *\n * @param config - Parser configuration. Accepts callbacks (see {@link ParserCallbacks})\n * and options like `maxBufferSize` (see {@link ParserConfig}).\n *\n * @returns A new EventSource parser, with `feed` and `reset` methods.\n * @public\n */\nexport function createParser(config: ParserConfig): EventSourceParser {\n if (typeof config === 'function') {\n throw new TypeError(\n '`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?',\n )\n }\n\n const {onEvent = noop, onError = noop, onRetry = noop, onComment, maxBufferSize} = config\n\n // Trailing bytes from prior `feed()` calls that did not yet form a complete line.\n // Stored as an array of fragments and only joined when a line terminator arrives.\n // Concatenating per-feed (`prefix + chunk`) is O(N²) when a single SSE line spans\n // many chunks (e.g. a large `data:` payload streamed in tiny slices, or an MCP-style\n // server that emits one giant content block). Buffering as fragments + joining once\n // makes the same workload linear.\n const pendingFragments: string[] = []\n\n // Running total of `pendingFragments` lengths, kept in sync with the array so the\n // `maxBufferSize` check doesn't have to walk the fragment list on every feed.\n let pendingFragmentsLength = 0\n\n let isFirstChunk = true\n let id: string | undefined\n let data = ''\n let dataLines = 0\n let eventType: string | undefined\n\n // Set after a `maxBufferSize` overflow. Once tripped, `feed()` throws until\n // `reset()` is called — see the comment on `maxBufferSize` in `ParserConfig`.\n let terminated = false\n\n /**\n * Feeds a chunk of the SSE stream to the parser. Any trailing bytes that do\n * not yet form a complete line are held back and prepended to the next chunk,\n * so callers can pass arbitrary slices of the stream without worrying about\n * line boundaries.\n *\n * Per the SSE spec, a UTF-8 BOM (0xEF 0xBB 0xBF) at the start of the very\n * first chunk is stripped before parsing.\n *\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream\n */\n function feed(chunk: string) {\n if (terminated) {\n throw new Error(\n 'Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.',\n )\n }\n\n if (isFirstChunk) {\n isFirstChunk = false\n // Match and strip UTF-8 BOM from the start of the stream, if present.\n // (Per the spec, this is only valid at the very start of the stream)\n if (\n chunk.charCodeAt(0) === 0xef &&\n chunk.charCodeAt(1) === 0xbb &&\n chunk.charCodeAt(2) === 0xbf\n ) {\n chunk = chunk.slice(3)\n }\n }\n\n // Hot path: no buffered prefix from a prior partial line. Hand the chunk\n // straight to `processLines`, exactly like the original implementation.\n // Zero new work in the common case (every chunk ends with `\\n\\n`).\n if (pendingFragments.length === 0) {\n const trailing = processLines(chunk)\n if (trailing !== '') {\n pendingFragments.push(trailing)\n pendingFragmentsLength = trailing.length\n }\n checkBufferSize()\n return\n }\n\n // We have a buffered prefix. If this chunk also has no terminator, append\n // to the buffer without concatenating — that's the O(N²) trap we're\n // avoiding (large single `data:` payload split across many tiny chunks).\n if (chunk.indexOf('\\n') === -1 && chunk.indexOf('\\r') === -1) {\n pendingFragments.push(chunk)\n pendingFragmentsLength += chunk.length\n checkBufferSize()\n return\n }\n\n // Terminator arrived. Join the accumulated fragments + this chunk once,\n // process, and buffer any new trailing partial line.\n pendingFragments.push(chunk)\n const input = pendingFragments.join('')\n pendingFragments.length = 0\n pendingFragmentsLength = 0\n const trailing = processLines(input)\n if (trailing !== '') {\n pendingFragments.push(trailing)\n pendingFragmentsLength = trailing.length\n }\n checkBufferSize()\n }\n\n function checkBufferSize() {\n if (maxBufferSize === undefined) return\n if (pendingFragmentsLength + data.length <= maxBufferSize) return\n\n terminated = true\n pendingFragments.length = 0\n pendingFragmentsLength = 0\n id = undefined\n data = ''\n dataLines = 0\n eventType = undefined\n onError(\n new ParseError(`Buffered data exceeded max buffer size of ${maxBufferSize} characters`, {\n type: 'max-buffer-size-exceeded',\n }),\n )\n }\n\n /**\n * Splits `chunk` into SSE lines and dispatches each to the appropriate handler.\n * Returns any trailing bytes that did not terminate with a line break, so the\n * caller can prepend them to the next chunk.\n *\n * The SSE spec permits three line terminators: `\\n`, `\\r`, and `\\r\\n`. Real-world\n * streams almost always use plain `\\n`, so we take a fast path when no `\\r` is\n * present in the chunk. The slow path is spec-correct but does more work per line.\n */\n function processLines(chunk: string): string {\n let searchIndex = 0\n\n // Fast path: LF-only chunk (the common case for typical SSE servers).\n // We can scan forward with a single `indexOf('\\n')` per line and inline\n // the hot-path branches for `data:` and `event:` without the CR bookkeeping\n // the slow path needs.\n if (chunk.indexOf('\\r') === -1) {\n let lfIndex = chunk.indexOf('\\n', searchIndex)\n while (lfIndex !== -1) {\n // Blank line: end-of-event marker. Dispatch the accumulated event (if any)\n // and reset the buffered fields. This is hoisted out of `parseLine` because\n // it's the single most common line shape after `data:` lines.\n if (searchIndex === lfIndex) {\n if (dataLines > 0) {\n onEvent({id, event: eventType, data})\n }\n id = undefined\n data = ''\n dataLines = 0\n eventType = undefined\n searchIndex = lfIndex + 1\n lfIndex = chunk.indexOf('\\n', searchIndex)\n continue\n }\n const firstCharCode = chunk.charCodeAt(searchIndex)\n if (isDataPrefix(chunk, searchIndex, firstCharCode)) {\n // `data:` line — append the value to the event's data buffer.\n // 'data:'.length === 5, 'data: '.length === 6\n const valueStart =\n chunk.charCodeAt(searchIndex + 5) === SPACE ? searchIndex + 6 : searchIndex + 5\n const value = chunk.slice(valueStart, lfIndex)\n // Fast path within a fast path: if this is the first data line AND the\n // next char is another LF (i.e. `data:foo\\n\\n`), dispatch immediately\n // without ever writing to the `data` buffer. This is the shape of a\n // typical single-line SSE event (ChatGPT-style streams, etc.) and is\n // hot enough to be worth the duplication.\n if (dataLines === 0 && chunk.charCodeAt(lfIndex + 1) === LF) {\n onEvent({id, event: eventType, data: value})\n id = undefined\n data = ''\n eventType = undefined\n searchIndex = lfIndex + 2\n lfIndex = chunk.indexOf('\\n', searchIndex)\n continue\n }\n // Multi-line data: concatenate with newline separator per spec.\n data = dataLines === 0 ? value : `${data}\\n${value}`\n dataLines++\n } else if (isEventPrefix(chunk, searchIndex, firstCharCode)) {\n // `event:` line — set the event type for the next dispatch. Per spec,\n // an empty value resets `event type` to its default (undefined here).\n // 'event:'.length === 6, 'event: '.length === 7\n eventType =\n chunk.slice(\n chunk.charCodeAt(searchIndex + 6) === SPACE ? searchIndex + 7 : searchIndex + 6,\n lfIndex,\n ) || undefined\n } else {\n // Everything else: `id:`, `retry:`, comment lines (`:` prefix), unknown\n // fields, or malformed lines. These are rarer and go through the full\n // per-line parser, which handles the SSE field grammar in detail.\n parseLine(chunk, searchIndex, lfIndex)\n }\n searchIndex = lfIndex + 1\n lfIndex = chunk.indexOf('\\n', searchIndex)\n }\n return chunk.slice(searchIndex)\n }\n\n // Slow path: the chunk contains at least one `\\r`, so lines may be terminated\n // by `\\r`, `\\n`, or `\\r\\n`. We locate the next terminator by looking at both\n // the nearest `\\r` and `\\n` and picking whichever comes first.\n while (searchIndex < chunk.length) {\n const crIndex = chunk.indexOf('\\r', searchIndex)\n const lfIndex = chunk.indexOf('\\n', searchIndex)\n\n let lineEnd = -1\n if (crIndex !== -1 && lfIndex !== -1) {\n lineEnd = crIndex < lfIndex ? crIndex : lfIndex\n } else if (crIndex !== -1) {\n // A trailing `\\r` at the very end of the chunk is ambiguous: it could be\n // a bare-CR terminator, or the first half of a `\\r\\n` whose `\\n` arrives\n // in the next chunk. Defer until we see more input.\n if (crIndex === chunk.length - 1) {\n lineEnd = -1\n } else {\n lineEnd = crIndex\n }\n } else if (lfIndex !== -1) {\n lineEnd = lfIndex\n }\n\n if (lineEnd === -1) {\n break\n }\n\n parseLine(chunk, searchIndex, lineEnd)\n searchIndex = lineEnd + 1\n // If we just consumed a `\\r` and the next char is `\\n`, skip it so the\n // pair is treated as a single terminator rather than an empty line.\n if (chunk.charCodeAt(searchIndex - 1) === CR && chunk.charCodeAt(searchIndex) === LF) {\n searchIndex++\n }\n }\n\n return chunk.slice(searchIndex)\n }\n\n function parseLine(chunk: string, start: number, end: number) {\n if (start === end) {\n dispatchEvent()\n return\n }\n\n const firstCharCode = chunk.charCodeAt(start)\n\n if (isDataPrefix(chunk, start, firstCharCode)) {\n // 'data:'.length === 5, 'data: '.length === 6\n const valueStart = chunk.charCodeAt(start + 5) === SPACE ? start + 6 : start + 5\n const value = chunk.slice(valueStart, end)\n data = dataLines === 0 ? value : `${data}\\n${value}`\n dataLines++\n return\n }\n\n if (isEventPrefix(chunk, start, firstCharCode)) {\n // 'event:'.length === 6, 'event: '.length === 7\n eventType =\n chunk.slice(chunk.charCodeAt(start + 6) === SPACE ? start + 7 : start + 6, end) || undefined\n return\n }\n\n // Fast path for \"id:\" — 'i' = 105, 'd' = 100, ':' = 58\n if (\n firstCharCode === 105 &&\n chunk.charCodeAt(start + 1) === 100 &&\n chunk.charCodeAt(start + 2) === 58\n ) {\n // 'id:'.length === 3, 'id: '.length === 4\n const value = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end)\n // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n // the field value. Otherwise, ignore the field.\n if (!value.includes('\\0')) id = value\n return\n }\n\n // Comment line — ':' = 58\n if (firstCharCode === 58) {\n if (onComment) {\n const line = chunk.slice(start, end)\n // skip ':' (+1), or ': ' (+2) when a space follows\n onComment(line.slice(chunk.charCodeAt(start + 1) === SPACE ? 2 : 1))\n }\n return\n }\n\n const line = chunk.slice(start, end)\n const fieldSeparatorIndex = line.indexOf(':')\n if (fieldSeparatorIndex === -1) {\n processField(line, '', line)\n return\n }\n\n const field = line.slice(0, fieldSeparatorIndex)\n // skip ':' (+1), or ': ' (+2) when a space follows\n const offset = line.charCodeAt(fieldSeparatorIndex + 1) === SPACE ? 2 : 1\n const value = line.slice(fieldSeparatorIndex + offset)\n processField(field, value, line)\n }\n\n function processField(field: string, value: string, line: string) {\n // Field names must be compared literally, with no case folding performed.\n switch (field) {\n case 'event':\n // Set the `event type` buffer to field value\n eventType = value || undefined\n break\n case 'data':\n data = dataLines === 0 ? value : `${data}\\n${value}`\n dataLines++\n break\n case 'id':\n // If the field value does not contain U+0000 NULL, then set the `ID` buffer to\n // the field value. Otherwise, ignore the field.\n if (!value.includes('\\0')) id = value\n break\n case 'retry':\n // If the field value consists of only ASCII digits, then interpret the field value as an\n // integer in base ten, and set the event stream's reconnection time to that integer.\n // Otherwise, ignore the field.\n if (/^\\d+$/.test(value)) {\n onRetry(parseInt(value, 10))\n } else {\n onError(\n new ParseError(`Invalid \\`retry\\` value: \"${value}\"`, {\n type: 'invalid-retry',\n value,\n line,\n }),\n )\n }\n break\n default:\n // Otherwise, the field is ignored.\n onError(\n new ParseError(\n `Unknown field \"${field.length > 20 ? `${field.slice(0, 20)}…` : field}\"`,\n {type: 'unknown-field', field, value, line},\n ),\n )\n break\n }\n }\n\n function dispatchEvent() {\n if (dataLines > 0) {\n onEvent({\n id,\n event: eventType,\n data,\n })\n }\n\n id = undefined\n data = ''\n dataLines = 0\n eventType = undefined\n }\n\n function reset(options: {consume?: boolean} = {}) {\n if (options.consume && pendingFragments.length > 0) {\n const incompleteLine = pendingFragments.join('')\n parseLine(incompleteLine, 0, incompleteLine.length)\n }\n\n isFirstChunk = true\n id = undefined\n data = ''\n dataLines = 0\n eventType = undefined\n pendingFragments.length = 0\n pendingFragmentsLength = 0\n terminated = false\n }\n\n return {feed, reset}\n}\n\n/**\n * Checks if `chunk` starts with the literal `data:` at index `i`.\n *\n * Equivalent to `chunk.startsWith('data:', i)`, but benchmarks show this\n * hand-unrolled char-code comparison is ~20% faster on common event types.\n * The caller passes `firstCharCode` (the code at `i`) so it can be reused\n * across prefix checks.\n *\n * ASCII: 'd' = 100, 'a' = 97, 't' = 116, 'a' = 97, ':' = 58\n */\nfunction isDataPrefix(chunk: string, i: number, firstCharCode: number): boolean {\n return (\n firstCharCode === 100 &&\n chunk.charCodeAt(i + 1) === 97 &&\n chunk.charCodeAt(i + 2) === 116 &&\n chunk.charCodeAt(i + 3) === 97 &&\n chunk.charCodeAt(i + 4) === 58\n )\n}\n\n/**\n * Checks if `chunk` starts with the literal `event:` at index `i`.\n *\n * See {@link isDataPrefix} for why this is hand-unrolled rather than using\n * `String.prototype.startsWith`.\n *\n * ASCII: 'e' = 101, 'v' = 118, 'e' = 101, 'n' = 110, 't' = 116, ':' = 58\n */\nfunction isEventPrefix(chunk: string, i: number, firstCharCode: number): boolean {\n return (\n firstCharCode === 101 &&\n chunk.charCodeAt(i + 1) === 118 &&\n chunk.charCodeAt(i + 2) === 101 &&\n chunk.charCodeAt(i + 3) === 110 &&\n chunk.charCodeAt(i + 4) === 116 &&\n chunk.charCodeAt(i + 5) === 58\n )\n}\n"],"names":["trailing","value","line"],"mappings":"AAWO,MAAM,mBAAmB,MAAM;AAAA,EAqBpC,YACE,SACA,SACA;AACA,UAAM,OAAO,GACb,KAAK,OAAO,cACZ,KAAK,OAAO,QAAQ,MACpB,KAAK,QAAQ,QAAQ,OACrB,KAAK,QAAQ,QAAQ,OACrB,KAAK,OAAO,QAAQ;AAAA,EACtB;AACF;ACnCA,MAAM,KAAK,IACL,KAAK,IACL,QAAQ;AAGd,SAAS,KAAK,MAAe;AAE7B;AAWO,SAAS,aAAa,QAAyC;AACpE,MAAI,OAAO,UAAW;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAIJ,QAAM,EAAC,UAAU,MAAM,UAAU,MAAM,UAAU,MAAM,WAAW,cAAA,IAAiB,QAQ7E,mBAA6B,CAAA;AAInC,MAAI,yBAAyB,GAEzB,eAAe,IACf,IACA,OAAO,IACP,YAAY,GACZ,WAIA,aAAa;AAajB,WAAS,KAAK,OAAe;AAC3B,QAAI;AACF,YAAM,IAAI;AAAA,QACR;AAAA,MAAA;AAoBJ,QAhBI,iBACF,eAAe,IAIb,MAAM,WAAW,CAAC,MAAM,OACxB,MAAM,WAAW,CAAC,MAAM,OACxB,MAAM,WAAW,CAAC,MAAM,QAExB,QAAQ,MAAM,MAAM,CAAC,KAOrB,iBAAiB,WAAW,GAAG;AACjC,YAAMA,YAAW,aAAa,KAAK;AAC/BA,oBAAa,OACf,iBAAiB,KAAKA,SAAQ,GAC9B,yBAAyBA,UAAS,SAEpC,gBAAA;AACA;AAAA,IACF;AAKA,QAAI,MAAM,QAAQ;AAAA,CAAI,MAAM,MAAM,MAAM,QAAQ,IAAI,MAAM,IAAI;AAC5D,uBAAiB,KAAK,KAAK,GAC3B,0BAA0B,MAAM,QAChC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AAkB,OAClB,MAAM,WAAW,IAAI,CAAC,MAAM,OAC5B,MAAM,WAAW,IAAI,CAAC,MAAM,OAC5B,MAAM,WAAW,IAAI,CAAC,MAAM,OAC5B,MAAM,WAAW,IAAI,CAAC,MAAM,OAC5B,MAAM,WAAW,IAAI,CAAC,MAAM;AAEhC;"}
|
|
@@ -291,7 +291,9 @@ export function createParser(config: ParserConfig): EventSourceParser {
|
|
|
291
291
|
) {
|
|
292
292
|
// 'id:'.length === 3, 'id: '.length === 4
|
|
293
293
|
const value = chunk.slice(chunk.charCodeAt(start + 3) === SPACE ? start + 4 : start + 3, end)
|
|
294
|
-
|
|
294
|
+
// If the field value does not contain U+0000 NULL, then set the `ID` buffer to
|
|
295
|
+
// the field value. Otherwise, ignore the field.
|
|
296
|
+
if (!value.includes('\0')) id = value
|
|
295
297
|
return
|
|
296
298
|
}
|
|
297
299
|
|
|
@@ -333,7 +335,7 @@ export function createParser(config: ParserConfig): EventSourceParser {
|
|
|
333
335
|
case 'id':
|
|
334
336
|
// If the field value does not contain U+0000 NULL, then set the `ID` buffer to
|
|
335
337
|
// the field value. Otherwise, ignore the field.
|
|
336
|
-
|
|
338
|
+
if (!value.includes('\0')) id = value
|
|
337
339
|
break
|
|
338
340
|
case 'retry':
|
|
339
341
|
// If the field value consists of only ASCII digits, then interpret the field value as an
|
|
@@ -74,7 +74,7 @@ class ClientRequestImpl {
|
|
|
74
74
|
}
|
|
75
75
|
this.rBody = form;
|
|
76
76
|
}
|
|
77
|
-
if (args.json) {
|
|
77
|
+
if (args.json !== void 0) {
|
|
78
78
|
this.rBody = JSON.stringify(args.json);
|
|
79
79
|
this.cType = "application/json";
|
|
80
80
|
}
|
|
@@ -90,9 +90,9 @@ class ClientRequestImpl {
|
|
|
90
90
|
if (args?.cookie) {
|
|
91
91
|
const cookies = [];
|
|
92
92
|
for (const [key, value] of Object.entries(args.cookie)) {
|
|
93
|
-
cookies.push((0, import_cookie.serialize)(key, value
|
|
93
|
+
cookies.push((0, import_cookie.serialize)(key, value));
|
|
94
94
|
}
|
|
95
|
-
headerValues["Cookie"] = cookies.join("
|
|
95
|
+
headerValues["Cookie"] = cookies.join("; ");
|
|
96
96
|
}
|
|
97
97
|
if (this.cType) {
|
|
98
98
|
headerValues["Content-Type"] = this.cType;
|
|
@@ -101,7 +101,7 @@ const documentMetadataTag = (tag, children, props, sort) => {
|
|
|
101
101
|
const string = new import_base.JSXNode(tag, restProps, (0, import_children.toArray)(children || [])).toString();
|
|
102
102
|
if (string instanceof Promise) {
|
|
103
103
|
return string.then(
|
|
104
|
-
(resString) => (0, import_html.raw)(
|
|
104
|
+
(resString) => (0, import_html.raw)(resString, [
|
|
105
105
|
...resString.callbacks || [],
|
|
106
106
|
insertIntoHead(tag, resString, restProps, precedence)
|
|
107
107
|
])
|
|
@@ -28,6 +28,8 @@ const cors = (options) => {
|
|
|
28
28
|
exposeHeaders: [],
|
|
29
29
|
...options
|
|
30
30
|
};
|
|
31
|
+
const exposeHeadersStr = opts.exposeHeaders?.length ? opts.exposeHeaders.join(",") : void 0;
|
|
32
|
+
const allowHeadersStr = opts.allowHeaders?.length ? opts.allowHeaders.join(",") : void 0;
|
|
31
33
|
const findAllowOrigin = ((optsOrigin) => {
|
|
32
34
|
if (typeof optsOrigin === "string") {
|
|
33
35
|
if (optsOrigin === "*") {
|
|
@@ -43,11 +45,12 @@ const cors = (options) => {
|
|
|
43
45
|
})(opts.origin);
|
|
44
46
|
const findAllowMethods = ((optsAllowMethods) => {
|
|
45
47
|
if (typeof optsAllowMethods === "function") {
|
|
46
|
-
return optsAllowMethods;
|
|
48
|
+
return async (origin, c) => (await optsAllowMethods(origin, c)).join(",");
|
|
47
49
|
} else if (Array.isArray(optsAllowMethods)) {
|
|
48
|
-
|
|
50
|
+
const methodsStr = optsAllowMethods.join(",");
|
|
51
|
+
return () => methodsStr;
|
|
49
52
|
} else {
|
|
50
|
-
return () =>
|
|
53
|
+
return () => "";
|
|
51
54
|
}
|
|
52
55
|
})(opts.allowMethods);
|
|
53
56
|
return async function cors2(c, next) {
|
|
@@ -61,8 +64,8 @@ const cors = (options) => {
|
|
|
61
64
|
if (opts.credentials) {
|
|
62
65
|
set("Access-Control-Allow-Credentials", "true");
|
|
63
66
|
}
|
|
64
|
-
if (
|
|
65
|
-
set("Access-Control-Expose-Headers",
|
|
67
|
+
if (exposeHeadersStr) {
|
|
68
|
+
set("Access-Control-Expose-Headers", exposeHeadersStr);
|
|
66
69
|
}
|
|
67
70
|
if (c.req.method === "OPTIONS") {
|
|
68
71
|
if (opts.origin !== "*") {
|
|
@@ -72,18 +75,18 @@ const cors = (options) => {
|
|
|
72
75
|
set("Access-Control-Max-Age", opts.maxAge.toString());
|
|
73
76
|
}
|
|
74
77
|
const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
|
|
75
|
-
if (allowMethods
|
|
76
|
-
set("Access-Control-Allow-Methods", allowMethods
|
|
78
|
+
if (allowMethods) {
|
|
79
|
+
set("Access-Control-Allow-Methods", allowMethods);
|
|
77
80
|
}
|
|
78
|
-
let
|
|
79
|
-
if (!
|
|
81
|
+
let headersStr = allowHeadersStr;
|
|
82
|
+
if (!headersStr) {
|
|
80
83
|
const requestHeaders = c.req.header("Access-Control-Request-Headers");
|
|
81
84
|
if (requestHeaders) {
|
|
82
|
-
|
|
85
|
+
headersStr = requestHeaders.split(",").map((h) => h.trim()).join(",");
|
|
83
86
|
}
|
|
84
87
|
}
|
|
85
|
-
if (
|
|
86
|
-
set("Access-Control-Allow-Headers",
|
|
88
|
+
if (headersStr) {
|
|
89
|
+
set("Access-Control-Allow-Headers", headersStr);
|
|
87
90
|
c.res.headers.append("Vary", "Access-Control-Request-Headers");
|
|
88
91
|
}
|
|
89
92
|
c.res.headers.delete("Content-Length");
|
|
@@ -31,18 +31,64 @@ const mergeBuffers = (buffer1, buffer2) => {
|
|
|
31
31
|
merged.set(buffer2, buffer1.byteLength);
|
|
32
32
|
return merged;
|
|
33
33
|
};
|
|
34
|
+
const CHUNK_SIZE = 256 * 1024;
|
|
34
35
|
const generateDigest = async (stream, generator) => {
|
|
35
36
|
if (!stream) {
|
|
36
37
|
return null;
|
|
37
38
|
}
|
|
38
39
|
let result = void 0;
|
|
40
|
+
let chunk;
|
|
41
|
+
let chunkLength = 0;
|
|
42
|
+
const digest = async (body) => {
|
|
43
|
+
result = await generator(mergeBuffers(result, body));
|
|
44
|
+
};
|
|
39
45
|
const reader = stream.getReader();
|
|
40
46
|
for (; ; ) {
|
|
41
47
|
const { value, done } = await reader.read();
|
|
42
48
|
if (done) {
|
|
43
49
|
break;
|
|
44
50
|
}
|
|
45
|
-
|
|
51
|
+
let offset = 0;
|
|
52
|
+
while (offset < value.byteLength) {
|
|
53
|
+
const remaining = value.byteLength - offset;
|
|
54
|
+
if (chunkLength === 0 && remaining >= CHUNK_SIZE) {
|
|
55
|
+
await digest(value.subarray(offset, offset + CHUNK_SIZE));
|
|
56
|
+
offset += CHUNK_SIZE;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
const requiredLength = chunkLength + remaining;
|
|
60
|
+
if (requiredLength < CHUNK_SIZE) {
|
|
61
|
+
if (!chunk) {
|
|
62
|
+
chunk = value.subarray(offset);
|
|
63
|
+
} else {
|
|
64
|
+
if (chunk.byteLength < requiredLength) {
|
|
65
|
+
const nextChunk = new Uint8Array(
|
|
66
|
+
new ArrayBuffer(Math.min(CHUNK_SIZE, Math.max(requiredLength, chunk.byteLength * 2)))
|
|
67
|
+
);
|
|
68
|
+
nextChunk.set(chunk.subarray(0, chunkLength));
|
|
69
|
+
chunk = nextChunk;
|
|
70
|
+
}
|
|
71
|
+
chunk.set(value.subarray(offset), chunkLength);
|
|
72
|
+
}
|
|
73
|
+
chunkLength = requiredLength;
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
const length = CHUNK_SIZE - chunkLength;
|
|
77
|
+
if (chunk?.byteLength !== CHUNK_SIZE) {
|
|
78
|
+
const nextChunk = new Uint8Array(new ArrayBuffer(CHUNK_SIZE));
|
|
79
|
+
if (chunk) {
|
|
80
|
+
nextChunk.set(chunk.subarray(0, chunkLength));
|
|
81
|
+
}
|
|
82
|
+
chunk = nextChunk;
|
|
83
|
+
}
|
|
84
|
+
chunk.set(value.subarray(offset, offset + length), chunkLength);
|
|
85
|
+
await digest(chunk);
|
|
86
|
+
chunkLength = 0;
|
|
87
|
+
offset += length;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (chunk && chunkLength > 0) {
|
|
91
|
+
await digest(chunk.subarray(0, chunkLength));
|
|
46
92
|
}
|
|
47
93
|
if (!result) {
|
|
48
94
|
return null;
|
|
@@ -159,14 +159,17 @@ function getPermissionsPolicyDirectives(policy) {
|
|
|
159
159
|
return Object.entries(policy).map(([directive, value]) => {
|
|
160
160
|
const kebabDirective = camelToKebab(directive);
|
|
161
161
|
if (typeof value === "boolean") {
|
|
162
|
-
return `${kebabDirective}=${value ? "*" : "
|
|
162
|
+
return `${kebabDirective}=${value ? "*" : "()"}`;
|
|
163
163
|
}
|
|
164
164
|
if (Array.isArray(value)) {
|
|
165
165
|
if (value.length === 0) {
|
|
166
166
|
return `${kebabDirective}=()`;
|
|
167
167
|
}
|
|
168
|
-
if (value.length === 1 &&
|
|
169
|
-
return `${kebabDirective}
|
|
168
|
+
if (value.length === 1 && value[0] === "*") {
|
|
169
|
+
return `${kebabDirective}=*`;
|
|
170
|
+
}
|
|
171
|
+
if (value.length === 1 && value[0] === "none") {
|
|
172
|
+
return `${kebabDirective}=()`;
|
|
170
173
|
}
|
|
171
174
|
const allowlist = value.map((item) => ["self", "src"].includes(item) ? item : `"${item}"`);
|
|
172
175
|
return `${kebabDirective}=(${allowlist.join(" ")})`;
|
|
@@ -142,13 +142,13 @@ const checkOptionalParameter = (path) => {
|
|
|
142
142
|
if (segment !== "" && !/\:/.test(segment)) {
|
|
143
143
|
basePath += "/" + segment;
|
|
144
144
|
} else if (/\:/.test(segment)) {
|
|
145
|
-
if (
|
|
145
|
+
if (segment.charCodeAt(segment.length - 1) === 63) {
|
|
146
146
|
if (results.length === 0 && basePath === "") {
|
|
147
147
|
results.push("/");
|
|
148
148
|
} else {
|
|
149
149
|
results.push(basePath);
|
|
150
150
|
}
|
|
151
|
-
const optionalSegment = segment.
|
|
151
|
+
const optionalSegment = segment.slice(0, -1);
|
|
152
152
|
basePath += "/" + optionalSegment;
|
|
153
153
|
results.push(basePath);
|
|
154
154
|
} else {
|
|
@@ -60,7 +60,7 @@ var ClientRequestImpl = class {
|
|
|
60
60
|
}
|
|
61
61
|
this.rBody = form;
|
|
62
62
|
}
|
|
63
|
-
if (args.json) {
|
|
63
|
+
if (args.json !== void 0) {
|
|
64
64
|
this.rBody = JSON.stringify(args.json);
|
|
65
65
|
this.cType = "application/json";
|
|
66
66
|
}
|
|
@@ -76,9 +76,9 @@ var ClientRequestImpl = class {
|
|
|
76
76
|
if (args?.cookie) {
|
|
77
77
|
const cookies = [];
|
|
78
78
|
for (const [key, value] of Object.entries(args.cookie)) {
|
|
79
|
-
cookies.push(serialize(key, value
|
|
79
|
+
cookies.push(serialize(key, value));
|
|
80
80
|
}
|
|
81
|
-
headerValues["Cookie"] = cookies.join("
|
|
81
|
+
headerValues["Cookie"] = cookies.join("; ");
|
|
82
82
|
}
|
|
83
83
|
if (this.cType) {
|
|
84
84
|
headerValues["Content-Type"] = this.cType;
|
|
@@ -78,7 +78,7 @@ var documentMetadataTag = (tag, children, props, sort) => {
|
|
|
78
78
|
const string = new JSXNode(tag, restProps, toArray(children || [])).toString();
|
|
79
79
|
if (string instanceof Promise) {
|
|
80
80
|
return string.then(
|
|
81
|
-
(resString) => raw(
|
|
81
|
+
(resString) => raw(resString, [
|
|
82
82
|
...resString.callbacks || [],
|
|
83
83
|
insertIntoHead(tag, resString, restProps, precedence)
|
|
84
84
|
])
|
|
@@ -7,6 +7,8 @@ var cors = (options) => {
|
|
|
7
7
|
exposeHeaders: [],
|
|
8
8
|
...options
|
|
9
9
|
};
|
|
10
|
+
const exposeHeadersStr = opts.exposeHeaders?.length ? opts.exposeHeaders.join(",") : void 0;
|
|
11
|
+
const allowHeadersStr = opts.allowHeaders?.length ? opts.allowHeaders.join(",") : void 0;
|
|
10
12
|
const findAllowOrigin = ((optsOrigin) => {
|
|
11
13
|
if (typeof optsOrigin === "string") {
|
|
12
14
|
if (optsOrigin === "*") {
|
|
@@ -22,11 +24,12 @@ var cors = (options) => {
|
|
|
22
24
|
})(opts.origin);
|
|
23
25
|
const findAllowMethods = ((optsAllowMethods) => {
|
|
24
26
|
if (typeof optsAllowMethods === "function") {
|
|
25
|
-
return optsAllowMethods;
|
|
27
|
+
return async (origin, c) => (await optsAllowMethods(origin, c)).join(",");
|
|
26
28
|
} else if (Array.isArray(optsAllowMethods)) {
|
|
27
|
-
|
|
29
|
+
const methodsStr = optsAllowMethods.join(",");
|
|
30
|
+
return () => methodsStr;
|
|
28
31
|
} else {
|
|
29
|
-
return () =>
|
|
32
|
+
return () => "";
|
|
30
33
|
}
|
|
31
34
|
})(opts.allowMethods);
|
|
32
35
|
return async function cors2(c, next) {
|
|
@@ -40,8 +43,8 @@ var cors = (options) => {
|
|
|
40
43
|
if (opts.credentials) {
|
|
41
44
|
set("Access-Control-Allow-Credentials", "true");
|
|
42
45
|
}
|
|
43
|
-
if (
|
|
44
|
-
set("Access-Control-Expose-Headers",
|
|
46
|
+
if (exposeHeadersStr) {
|
|
47
|
+
set("Access-Control-Expose-Headers", exposeHeadersStr);
|
|
45
48
|
}
|
|
46
49
|
if (c.req.method === "OPTIONS") {
|
|
47
50
|
if (opts.origin !== "*") {
|
|
@@ -51,18 +54,18 @@ var cors = (options) => {
|
|
|
51
54
|
set("Access-Control-Max-Age", opts.maxAge.toString());
|
|
52
55
|
}
|
|
53
56
|
const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
|
|
54
|
-
if (allowMethods
|
|
55
|
-
set("Access-Control-Allow-Methods", allowMethods
|
|
57
|
+
if (allowMethods) {
|
|
58
|
+
set("Access-Control-Allow-Methods", allowMethods);
|
|
56
59
|
}
|
|
57
|
-
let
|
|
58
|
-
if (!
|
|
60
|
+
let headersStr = allowHeadersStr;
|
|
61
|
+
if (!headersStr) {
|
|
59
62
|
const requestHeaders = c.req.header("Access-Control-Request-Headers");
|
|
60
63
|
if (requestHeaders) {
|
|
61
|
-
|
|
64
|
+
headersStr = requestHeaders.split(",").map((h) => h.trim()).join(",");
|
|
62
65
|
}
|
|
63
66
|
}
|
|
64
|
-
if (
|
|
65
|
-
set("Access-Control-Allow-Headers",
|
|
67
|
+
if (headersStr) {
|
|
68
|
+
set("Access-Control-Allow-Headers", headersStr);
|
|
66
69
|
c.res.headers.append("Vary", "Access-Control-Request-Headers");
|
|
67
70
|
}
|
|
68
71
|
c.res.headers.delete("Content-Length");
|
|
@@ -10,18 +10,64 @@ var mergeBuffers = (buffer1, buffer2) => {
|
|
|
10
10
|
merged.set(buffer2, buffer1.byteLength);
|
|
11
11
|
return merged;
|
|
12
12
|
};
|
|
13
|
+
var CHUNK_SIZE = 256 * 1024;
|
|
13
14
|
var generateDigest = async (stream, generator) => {
|
|
14
15
|
if (!stream) {
|
|
15
16
|
return null;
|
|
16
17
|
}
|
|
17
18
|
let result = void 0;
|
|
19
|
+
let chunk;
|
|
20
|
+
let chunkLength = 0;
|
|
21
|
+
const digest = async (body) => {
|
|
22
|
+
result = await generator(mergeBuffers(result, body));
|
|
23
|
+
};
|
|
18
24
|
const reader = stream.getReader();
|
|
19
25
|
for (; ; ) {
|
|
20
26
|
const { value, done } = await reader.read();
|
|
21
27
|
if (done) {
|
|
22
28
|
break;
|
|
23
29
|
}
|
|
24
|
-
|
|
30
|
+
let offset = 0;
|
|
31
|
+
while (offset < value.byteLength) {
|
|
32
|
+
const remaining = value.byteLength - offset;
|
|
33
|
+
if (chunkLength === 0 && remaining >= CHUNK_SIZE) {
|
|
34
|
+
await digest(value.subarray(offset, offset + CHUNK_SIZE));
|
|
35
|
+
offset += CHUNK_SIZE;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
const requiredLength = chunkLength + remaining;
|
|
39
|
+
if (requiredLength < CHUNK_SIZE) {
|
|
40
|
+
if (!chunk) {
|
|
41
|
+
chunk = value.subarray(offset);
|
|
42
|
+
} else {
|
|
43
|
+
if (chunk.byteLength < requiredLength) {
|
|
44
|
+
const nextChunk = new Uint8Array(
|
|
45
|
+
new ArrayBuffer(Math.min(CHUNK_SIZE, Math.max(requiredLength, chunk.byteLength * 2)))
|
|
46
|
+
);
|
|
47
|
+
nextChunk.set(chunk.subarray(0, chunkLength));
|
|
48
|
+
chunk = nextChunk;
|
|
49
|
+
}
|
|
50
|
+
chunk.set(value.subarray(offset), chunkLength);
|
|
51
|
+
}
|
|
52
|
+
chunkLength = requiredLength;
|
|
53
|
+
break;
|
|
54
|
+
}
|
|
55
|
+
const length = CHUNK_SIZE - chunkLength;
|
|
56
|
+
if (chunk?.byteLength !== CHUNK_SIZE) {
|
|
57
|
+
const nextChunk = new Uint8Array(new ArrayBuffer(CHUNK_SIZE));
|
|
58
|
+
if (chunk) {
|
|
59
|
+
nextChunk.set(chunk.subarray(0, chunkLength));
|
|
60
|
+
}
|
|
61
|
+
chunk = nextChunk;
|
|
62
|
+
}
|
|
63
|
+
chunk.set(value.subarray(offset, offset + length), chunkLength);
|
|
64
|
+
await digest(chunk);
|
|
65
|
+
chunkLength = 0;
|
|
66
|
+
offset += length;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (chunk && chunkLength > 0) {
|
|
70
|
+
await digest(chunk.subarray(0, chunkLength));
|
|
25
71
|
}
|
|
26
72
|
if (!result) {
|
|
27
73
|
return null;
|
|
@@ -137,14 +137,17 @@ function getPermissionsPolicyDirectives(policy) {
|
|
|
137
137
|
return Object.entries(policy).map(([directive, value]) => {
|
|
138
138
|
const kebabDirective = camelToKebab(directive);
|
|
139
139
|
if (typeof value === "boolean") {
|
|
140
|
-
return `${kebabDirective}=${value ? "*" : "
|
|
140
|
+
return `${kebabDirective}=${value ? "*" : "()"}`;
|
|
141
141
|
}
|
|
142
142
|
if (Array.isArray(value)) {
|
|
143
143
|
if (value.length === 0) {
|
|
144
144
|
return `${kebabDirective}=()`;
|
|
145
145
|
}
|
|
146
|
-
if (value.length === 1 &&
|
|
147
|
-
return `${kebabDirective}
|
|
146
|
+
if (value.length === 1 && value[0] === "*") {
|
|
147
|
+
return `${kebabDirective}=*`;
|
|
148
|
+
}
|
|
149
|
+
if (value.length === 1 && value[0] === "none") {
|
|
150
|
+
return `${kebabDirective}=()`;
|
|
148
151
|
}
|
|
149
152
|
const allowlist = value.map((item) => ["self", "src"].includes(item) ? item : `"${item}"`);
|
|
150
153
|
return `${kebabDirective}=(${allowlist.join(" ")})`;
|
|
@@ -2,13 +2,13 @@ export type PermissionsPolicyDirective = StandardizedFeatures | ProposedFeatures
|
|
|
2
2
|
/**
|
|
3
3
|
* These features have been declared in a published version of the respective specification.
|
|
4
4
|
*/
|
|
5
|
-
type StandardizedFeatures = 'accelerometer' | 'ambientLightSensor' | 'attributionReporting' | 'autoplay' | 'battery' | 'bluetooth' | 'camera' | 'chUa' | 'chUaArch' | 'chUaBitness' | 'chUaFullVersion' | 'chUaFullVersionList' | 'chUaMobile' | 'chUaModel' | 'chUaPlatform' | 'chUaPlatformVersion' | 'chUaWow64' | 'computePressure' | 'crossOriginIsolated' | 'directSockets' | 'displayCapture' | 'encryptedMedia' | 'executionWhileNotRendered' | 'executionWhileOutOfViewport' | 'fullscreen' | 'geolocation' | 'gyroscope' | 'hid' | 'identityCredentialsGet' | 'idleDetection' | 'keyboardMap' | 'magnetometer' | 'microphone' | 'midi' | 'navigationOverride' | 'payment' | 'pictureInPicture' | 'publickeyCredentialsGet' | 'screenWakeLock' | 'serial' | 'storageAccess' | 'syncXhr' | 'usb' | 'webShare' | 'windowManagement' | 'xrSpatialTracking';
|
|
5
|
+
type StandardizedFeatures = 'accelerometer' | 'ambientLightSensor' | 'attributionReporting' | 'autoplay' | 'battery' | 'bluetooth' | 'camera' | 'chUa' | 'chUaArch' | 'chUaBitness' | 'chUaFullVersion' | 'chUaFullVersionList' | 'chUaHighEntropyValues' | 'chUaMobile' | 'chUaModel' | 'chUaPlatform' | 'chUaPlatformVersion' | 'chUaWow64' | 'computePressure' | 'crossOriginIsolated' | 'directSockets' | 'displayCapture' | 'encryptedMedia' | 'executionWhileNotRendered' | 'executionWhileOutOfViewport' | 'fullscreen' | 'geolocation' | 'gyroscope' | 'hid' | 'identityCredentialsGet' | 'idleDetection' | 'keyboardMap' | 'magnetometer' | 'mediasession' | 'microphone' | 'midi' | 'navigationOverride' | 'otpCredentials' | 'payment' | 'pictureInPicture' | 'publickeyCredentialsGet' | 'screenWakeLock' | 'serial' | 'storageAccess' | 'syncXhr' | 'tools' | 'usb' | 'webShare' | 'windowManagement' | 'xrSpatialTracking';
|
|
6
6
|
/**
|
|
7
7
|
* These features have been proposed, but the definitions have not yet been integrated into their respective specs.
|
|
8
8
|
*/
|
|
9
|
-
type ProposedFeatures = 'clipboardRead' | 'clipboardWrite' | 'gamepad' | 'sharedAutofill' | 'speakerSelection';
|
|
9
|
+
type ProposedFeatures = 'autofill' | 'clipboardRead' | 'clipboardWrite' | 'deferredFetch' | 'gamepad' | 'languageDetector' | 'languageModel' | 'manualText' | 'rewriter' | 'sharedAutofill' | 'speakerSelection' | 'summarizer' | 'translator' | 'writer';
|
|
10
10
|
/**
|
|
11
11
|
* These features generally have an explainer only, but may be available for experimentation by web developers.
|
|
12
12
|
*/
|
|
13
|
-
type ExperimentalFeatures = 'allScreensCapture' | 'browsingTopics' | 'capturedSurfaceControl' | 'conversionMeasurement' | 'digitalCredentialsGet' | 'focusWithoutUserActivation' | 'joinAdInterestGroup' | 'localFonts' | 'runAdAuction' | 'smartCard' | 'syncScript' | 'trustTokenRedemption' | 'unload' | 'verticalScroll';
|
|
13
|
+
type ExperimentalFeatures = 'allScreensCapture' | 'browsingTopics' | 'capturedSurfaceControl' | 'conversionMeasurement' | 'digitalCredentialsCreate' | 'digitalCredentialsGet' | 'focusWithoutUserActivation' | 'joinAdInterestGroup' | 'localFonts' | 'monetization' | 'runAdAuction' | 'smartCard' | 'syncScript' | 'trustTokenRedemption' | 'unload' | 'verticalScroll';
|
|
14
14
|
export {};
|
|
@@ -108,13 +108,13 @@ var checkOptionalParameter = (path) => {
|
|
|
108
108
|
if (segment !== "" && !/\:/.test(segment)) {
|
|
109
109
|
basePath += "/" + segment;
|
|
110
110
|
} else if (/\:/.test(segment)) {
|
|
111
|
-
if (
|
|
111
|
+
if (segment.charCodeAt(segment.length - 1) === 63) {
|
|
112
112
|
if (results.length === 0 && basePath === "") {
|
|
113
113
|
results.push("/");
|
|
114
114
|
} else {
|
|
115
115
|
results.push(basePath);
|
|
116
116
|
}
|
|
117
|
-
const optionalSegment = segment.
|
|
117
|
+
const optionalSegment = segment.slice(0, -1);
|
|
118
118
|
basePath += "/" + optionalSegment;
|
|
119
119
|
results.push(basePath);
|
|
120
120
|
} else {
|