Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add DenoIO #380

Merged
merged 3 commits into from
Dec 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/theme/layouts/default.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@
PlatformIO <em>(Abstract)</em>
</a>
</li>
<li class="tsd-kind-class">
<a href="/classes/core.denoio.html" class="tsd-kind-icon{{#ifCond url '===' 'classes/core.denoio.html'}} active{{/ifCond}}">
DenoIO
</a>
</li>
<li class="tsd-kind-class">
<a href="/classes/core.nodeio.html" class="tsd-kind-icon{{#ifCond url '===' 'classes/core.nodeio.html'}} active{{/ifCond}}">
NodeIO
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export {
COPY_IDENTITY,
} from './properties';
export { Graph, GraphEdge } from 'property-graph';
export { PlatformIO, NodeIO, WebIO, ReaderContext, WriterContext } from './io';
export { DenoIO, PlatformIO, NodeIO, WebIO, ReaderContext, WriterContext } from './io';
export {
BufferUtils,
ColorUtils,
Expand Down
69 changes: 69 additions & 0 deletions packages/core/src/io/deno-io.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { PlatformIO } from '.';

declare global {
const Deno: {
readFile: (path: string) => Promise<Uint8Array>;
readTextFile: (path: string) => Promise<string>;
};
}

interface Path {
resolve(directory: string, path: string): string;
dirname(uri: string): string;
}

/**
* # DenoIO
*
* *I/O service for Deno.*
*
* The most common use of the I/O service is to read/write a {@link Document} with a given path.
* Methods are also available for converting in-memory representations of raw glTF files, both
* binary (*ArrayBuffer*) and JSON ({@link JSONDocument}).
*
* Usage:
*
* ```typescript
* import { DenoIO } from 'https://esm.sh/@gltf-transform/core';
* import * as path from 'https://deno.land/std/path/mod.ts';
*
* const io = new DenoIO(path);
*
* // Read.
* let document;
* document = io.read('model.glb'); // → Document
* document = io.readBinary(glb); // Uint8Array → Document
*
* // Write.
* const glb = io.writeBinary(document); // Document → Uint8Array
* ```
*
* @category I/O
*/
export class DenoIO extends PlatformIO {
private _path: Path;

constructor(path: unknown) {
super();
this._path = path as Path;
}

protected async readURI(uri: string, type: 'view'): Promise<Uint8Array>;
protected async readURI(uri: string, type: 'text'): Promise<string>;
protected async readURI(uri: string, type: 'view' | 'text'): Promise<Uint8Array | string> {
switch (type) {
case 'view':
return Deno.readFile(uri);
case 'text':
return Deno.readTextFile(uri);
}
}

protected resolve(directory: string, path: string): string {
return this._path.resolve(directory, path);
}

protected dirname(uri: string): string {
return this._path.dirname(uri);
}
}
1 change: 1 addition & 0 deletions packages/core/src/io/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export { NodeIO } from './node-io';
export { DenoIO } from './deno-io';
export { PlatformIO } from './platform-io';
export { WebIO } from './web-io';
export { ReaderOptions } from './reader';
Expand Down
77 changes: 18 additions & 59 deletions packages/core/src/io/node-io.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { Format } from '../constants';
import { Document } from '../document';
import { JSONDocument } from '../json-document';
import { GLTF } from '../types/gltf';
import { FileUtils } from '../utils/';
import { PlatformIO } from './platform-io';

Expand Down Expand Up @@ -37,12 +35,6 @@ export class NodeIO extends PlatformIO {
private _fs;
private _path;

/** @hidden */
public lastReadBytes = 0;

/** @hidden */
public lastWriteBytes = 0;

/** Constructs a new NodeIO service. Instances are reusable. */
constructor() {
super();
Expand All @@ -51,72 +43,39 @@ export class NodeIO extends PlatformIO {
this._path = require('path');
}

/**********************************************************************************************
* Public.
*/

/** Loads a local path and returns a {@link Document} instance. */
public async read(uri: string): Promise<Document> {
return await this.readJSON(await this.readAsJSON(uri));
protected async readURI(uri: string, type: 'view'): Promise<Uint8Array>;
protected async readURI(uri: string, type: 'text'): Promise<string>;
protected async readURI(uri: string, type: 'view' | 'text'): Promise<Uint8Array | string> {
switch (type) {
case 'view':
return this._fs.readFile(uri);
case 'text':
return this._fs.readFile(uri, 'utf8');
}
}

/** Loads a local path and returns a {@link JSONDocument} struct, without parsing. */
public async readAsJSON(uri: string): Promise<JSONDocument> {
const isGLB = !!(uri.match(/\.glb$/) || uri.match(/^data:application\/octet-stream;/));
return isGLB ? this._readGLB(uri) : this._readGLTF(uri);
protected resolve(directory: string, path: string): string {
return this._path.resolve(directory, path);
}

/** Writes a {@link Document} instance to a local path. */
public async write(uri: string, doc: Document): Promise<void> {
const isGLB = !!uri.match(/\.glb$/);
await (isGLB ? this._writeGLB(uri, doc) : this._writeGLTF(uri, doc));
protected dirname(uri: string): string {
return this._path.dirname(uri);
}

/**********************************************************************************************
* Protected.
* Public.
*/

/** @internal */
private async _readResourcesExternal(jsonDoc: JSONDocument, dir: string): Promise<void> {
const images = jsonDoc.json.images || [];
const buffers = jsonDoc.json.buffers || [];
const resources = [...images, ...buffers].map(async (resource: GLTF.IBuffer | GLTF.IImage) => {
if (resource.uri && !resource.uri.match(/data:/)) {
const absURI = this._path.resolve(dir, resource.uri);
jsonDoc.resources[resource.uri] = await this._fs.readFile(absURI);
this.lastReadBytes += jsonDoc.resources[resource.uri].byteLength;
}
});
await Promise.all(resources);
/** Writes a {@link Document} instance to a local path. */
public async write(uri: string, doc: Document): Promise<void> {
const isGLB = !!uri.match(/\.glb$/);
await (isGLB ? this._writeGLB(uri, doc) : this._writeGLTF(uri, doc));
}

/**********************************************************************************************
* Private.
*/

/** @internal */
private async _readGLB(uri: string): Promise<JSONDocument> {
const buffer: Buffer = await this._fs.readFile(uri);
this.lastReadBytes = buffer.byteLength;
const jsonDoc = this._binaryToJSON(buffer);
// Read external resources first, before Data URIs are replaced.
await this._readResourcesExternal(jsonDoc, this._path.dirname(uri));
await this._readResourcesInternal(jsonDoc);
return jsonDoc;
}

/** @internal */
private async _readGLTF(uri: string): Promise<JSONDocument> {
this.lastReadBytes = 0;
const jsonContent = await this._fs.readFile(uri, 'utf8');
this.lastReadBytes += jsonContent.length;
const jsonDoc = { json: JSON.parse(jsonContent), resources: {} } as JSONDocument;
// Read external resources first, before Data URIs are replaced.
await this._readResourcesExternal(jsonDoc, this._path.dirname(uri));
await this._readResourcesInternal(jsonDoc);
return jsonDoc;
}

/** @internal */
private async _writeGLTF(uri: string, doc: Document): Promise<void> {
this.lastWriteBytes = 0;
Expand Down
Loading