From 640a4a41cac4076a363fb2e4ec8b1893ad51e43c Mon Sep 17 00:00:00 2001 From: Blayne Chard Date: Fri, 21 Jul 2023 00:12:16 +1200 Subject: [PATCH] fix(source-memory): allow creating source with string url --- packages/source-memory/src/__test__/memory.test.ts | 10 ++++++++++ packages/source-memory/src/index.ts | 13 ++++++++++--- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/packages/source-memory/src/__test__/memory.test.ts b/packages/source-memory/src/__test__/memory.test.ts index 31576a6f..69cb9110 100644 --- a/packages/source-memory/src/__test__/memory.test.ts +++ b/packages/source-memory/src/__test__/memory.test.ts @@ -29,4 +29,14 @@ describe('SourceMemory', () => { const bytesNegative = await source.fetch(-2); assert.equal(Buffer.from(bytesNegative).toString(), '23'); }); + + it('should allow string names', () => { + const array = new Uint8Array(chars.split('').map((c) => c.charCodeAt(0))); + + const source = new SourceMemory('memory://test.txt', array); + assert.equal(source.url.href, 'memory://test.txt'); + + const sourceRel = new SourceMemory('test.txt', array); + assert.equal(sourceRel.url.href, 'memory://test.txt'); + }); }); diff --git a/packages/source-memory/src/index.ts b/packages/source-memory/src/index.ts index 3b44b64e..0528593b 100644 --- a/packages/source-memory/src/index.ts +++ b/packages/source-memory/src/index.ts @@ -1,4 +1,11 @@ -import { Source, SourceError, SourceMetadata } from '@chunkd/source'; +import { Source, SourceError, SourceMetadata, tryParseUrl } from '@chunkd/source'; + +function parseMemoryUrl(s: string | URL): URL { + if (typeof s !== 'string') return s; + const url = tryParseUrl(s); + if (url) return url; + return new URL('memory://' + s); +} export class SourceMemory implements Source { url: URL; @@ -12,9 +19,9 @@ export class SourceMemory implements Source { return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); } - constructor(url: URL, bytes: Buffer | Uint8Array | ArrayBuffer) { + constructor(url: URL | string, bytes: Buffer | Uint8Array | ArrayBuffer) { const buf = SourceMemory.toArrayBuffer(bytes ?? new Uint8Array()); - this.url = url; + this.url = parseMemoryUrl(url); this.data = buf; this.metadata = { size: buf.byteLength }; }